HttpClient实现两种远程调用

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

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

Get请求:

List 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 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);

}


Post请求:

List 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 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);

}



你可能感兴趣的:(网络请求)