1. 程式人生 > >HttpClient實現兩種遠端呼叫

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{

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

}