HttpClientを使用してJavaでインターフェイスを呼び出す
1.HttpClientによって提供される主な機能
(1)すべてのHTTPメソッド(GET、POST、PUT、DELETEなど)が実装されています
(2)自動操舵をサポート
(3)HTTPSプロトコルをサポートする
(4)プロキシサーバー等をサポートします。
ビジネスに取り掛かろう!!!!コードをアップロード
public static String sendPutForm(String url, Map<String,String> map, String encoding) throws ParseException, IOException {
String body = "";
// 打印了一下我推送的json数据
log.info("我推送的json数据:" + map);
log.info("我推送的url:" + url);
CloseableHttpResponse response = null;
///获得Http客户端
CloseableHttpClient client = HttpClients.createDefault();
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
parameters.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 配置信息
// 设置连接超时时间(单位毫秒)
// 设置请求超时时间(单位毫秒)
// socket读写超时时间(单位毫秒)
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000).setConnectionRequestTimeout(50000)
.setSocketTimeout(50000).build();
// 向指定资源位置上传内容// 创建Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setEntity(formEntity);
try {
response = client.execute(httpPost);
// 通过response中的getEntity()方法获取返回值
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
httpPost.abort();
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
log.info("body:" + body);
return body;
}