接口參數(shù)使用postman調(diào)用如圖所示,只能使用form-data格式調(diào)用
使用java代碼發(fā)送http請求實(shí)現(xiàn)此種方式的接口調(diào)用文章來源:http://www.zghlxwxcb.cn/news/detail-528242.html
public static String doPostForm(String url, HashMap<String, String> map) throws Exception {
String result = "";
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
// client = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(url);
HttpPost httpPost = new HttpPost(uriBuilder.build());
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Charset", "UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
params.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
try {
response = client.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "UTF-8");
}
}
} catch (ClientProtocolException e) {
throw new RuntimeException("創(chuàng)建連接失敗" + e);
} catch (IOException e) {
throw new RuntimeException("創(chuàng)建連接失敗" + e);
}
return result;
}
特別說明:form的Content-Type屬性為編碼方式文章來源地址http://www.zghlxwxcb.cn/news/detail-528242.html
- 常用有兩種:application/x-www-form-urlencoded和multipart/form-data,默認(rèn)為application/x-www-form-urlencoded。
- x-www-form-urlencoded:當(dāng)action為get時(shí)候,瀏覽器用x-www-form-urlencoded的編碼方式把form數(shù)據(jù)轉(zhuǎn)換成一個(gè)字串(name1=value1&name2=value2…),然后把這個(gè)字串a(chǎn)ppend到url后面,用?分割,加載這個(gè)新的url。
- multipart/form-data:當(dāng)action為post時(shí)候,瀏覽器把form數(shù)據(jù)封裝到http body中,然后發(fā)送到server。 如果沒有type=file的控件,用默認(rèn)的application/x-www-form-urlencoded就可以了。 但是如果有type=file的話,就要用到multipart/form-data了。瀏覽器會(huì)把整個(gè)表單以控件為單位分割,并為每個(gè)部分加上Content-Disposition(form-data或者file),Content-Type(默認(rèn)為text/plain),name(控件name)等信息,并加上分割符(boundary)。
到了這里,關(guān)于Java請求調(diào)用參數(shù)格式為form-data類型的接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!