古詩詞大全網 - 四字成語 - httpclient怎麽設置post請求長度

httpclient怎麽設置post請求長度

HttpClient 是apache 組織下面的壹個用於處理HTTP 請求和響應的開源工具。所用jar包為mons-codec-1.6.jar。

發送Post請求代碼如下:

[java] view plain copy

package com.zkn.newlearn..google.common.collect.Lists;

/**

*

* @author zkn 2016-06-05

*

*/

public class HttpClientTest01 {

public static void main(String[] args) {

//創建HttpClient對象

CloseableHttpClient closeHttpClient = HttpClients.createDefault();

CloseableHttpResponse httpResponse = null;

//發送Post請求

HttpPost httpPost = new HttpPost("http://localhost:8080/MyWebxTest/getCityByProvinceEname.do");

//設置Post參數

List<NameValuePair> params = Lists.newArrayList();

params.add(new BasicNameValuePair("cityEname", "henan"));

try {

//轉換參數並設置編碼格式

httpPost.setEntity(new UrlEncodedFormEntity(params,Consts.UTF_8));

//執行Post請求 得到Response對象

httpResponse = closeHttpClient.execute(httpPost);

//httpResponse.getStatusLine() 響應頭信息

System.out.println(httpResponse.getStatusLine());

//返回對象 向上造型

HttpEntity httpEntity = httpResponse.getEntity();

if(httpEntity != null){

//響應輸入流

InputStream is = httpEntity.getContent();

//轉換為字符輸入流

BufferedReader br = new BufferedReader(new InputStreamReader(is,Consts.UTF_8));

String line = null;

while((line=br.readLine())!=null){

System.out.println(line);

}

//關閉輸入流

is.close();

}

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(httpResponse != null){

try {

httpResponse.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if(closeHttpClient != null){

try {

closeHttpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}