HttpClient实现两种远程调用

Http远程调用两种方式:Get 和Post请求

这里适用HttpClient实现两种请求。

Get请求:

List<BasicNameValuePair> params = new ArrayList<>();

params.add(new BasicNameValuePair("name","hello")); 

UrlEncodeFormEntity entity = new UrlEncodeFormEntity(params, HTTP.UTF.8);

String url = "localhost";

HttpGet request = new HttpGet(url + "?" + EntityUtils.toString(entity));

ResponseHandler<String> handler = new BasicResponseHandler();

CloseableHttpClient httpClient = HttpClients.createDefault();

try{

扫描二维码关注公众号,回复: 724790 查看本文章

    requet.setHeader("Accept", "application/json");

    String responseJson = httpClient.excute(request, handler);

} catch (IOException e){

    e.printStackTrace();

} finally {

    httpClient.getConnectionManager().closeExpiredConnections();

    httpClient.getConnectionManager().closeIdleConnections(30 , TimeUtil.SECONDS);

}


Post请求:

List<BasicNameValuePair> params = new ArrayList<>();

params.add(new BasicNameValuePair("name","hello")); 

UrlEncodeFormEntity entity = new UrlEncodeFormEntity(params, HTTP.UTF.8);

String url = "localhost";

HttpPost request = new HttpPost(url);

requet.setEntity(entity);

ResponseHandler<String> handler = new BasicResponseHandler();

CloseableHttpClient httpClient = HttpClients.createDefault();

try{

    requet.setHeader("Accept", "application/json");

    String responseJson = httpClient.excute(request, handler);

} catch (IOException e){

    e.printStackTrace();

} finally {

    httpClient.getConnectionManager().closeExpiredConnections();

    httpClient.getConnectionManager().closeIdleConnections(30 , TimeUtil.SECONDS);

}



猜你喜欢

转载自blog.csdn.net/qq_36349129/article/details/80285403