您的位置:首页 > 理论基础 > 计算机网络

一个使用HttpClient get post请求的实例

2017-04-18 15:31 344 查看
public static void main(String[] args) throws HttpException, IOException {
System.setProperty("http.proxySet", "true"); 
System.setProperty("http.proxyHost", "127.0.0.1"); 
System.setProperty("http.proxyPort", "8888");
String str="{\"adtCount\":1,\"chdCount\":0,"
+ "\"depCode\":\"BJS\",\"depDate\":\"2017-06-11\","
+ "\"desCode\":\"XIY\",\"gdsIpcc\":\"\",\"gdsPwd\":\"\","
+ "\"gdsSource\":\"3\",\"infCount\":0,\"maxSolutions\":0,\"returnDate\":\"\","
+ "\"sessionID\":\"taobao1704071101115568\",\"tripType\":\"1\"}";
NameValuePair[] params ={new NameValuePair("searchCondition",str)};
String data=doPost("url",params,10000);

        
JSONObject jo=JSONObject.fromObject(data);
System.out.println();

}

public String doGet(String url, List<NameValuePair> params)
throws HttpException, IOException {
String result = "";
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());

getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
getMethod.addRequestHeader("Content-type" , "text/html; charset=UTF-8"); 
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}

// result=new String(getMethod.getResponseBodyAsString().getBytes("gb2312"));
result = getMethod.getResponseBodyAsString();
} catch (HttpException e) {
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
getMethod = null;
}
return result;
}

public static String doPost(String url,NameValuePair[] params, int timeout)

throws HttpException, IOException {

log.debug("doPost---");

String response = "";

// (1)构造HttpClient的实例
HttpClient httpClient = new HttpClient();

httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);

log.info("url="+url);
// (2)创建POST方法的实例
PostMethod postMethod = new PostMethod(url);

// (3)设置http request头
List<Header> headers = new ArrayList<Header>();
// headers.add(new Header("tianjun_key", "tianjun_value"));

// httpClient.getHostConfiguration().getParams()

// .setParameter("http.default-headers", headers);

// 使用系统提供的默认的恢复策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0,false));
// 字符集
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

postMethod.setRequestHeader("Connection", "close"); // or "Keep-Alive"

for (NameValuePair nvp : params) {
log.info(nvp);
}

postMethod.setRequestBody(params);

try {
// (4)执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
log.info("executeMethod httpClient.getState()="
+ httpClient.getState());
if (statusCode != HttpStatus.SC_OK) {
throw new HttpException(String.valueOf(statusCode));
}

// (5)读取response头信息
// Header headerResponse = postMethod
// .getResponseHeader("");
// String headerStr = headerResponse.getValue();
// (6)读取内容
InputStream is = postMethod.getResponseBodyAsStream();
InputStreamReader inReader = new InputStreamReader(is, "UTF-8");
BufferedReader bufReader = new BufferedReader(inReader);

String temp = "";
while ((temp = bufReader.readLine()) != null) {
response = response + temp;
}

// response = postMethod.getResponseBodyAsStream();
// (7) 处理内容
// System.out.println(headerStr);
// System.out.println(new String(responseBody));
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
throw new IOException("连接错误:" + e.getStackTrace());
} catch (IOException e) {
throw new IOException("连接错误:" + e.getStackTrace());
} catch (Exception e) {
e.printStackTrace();
throw new IOException("连接错误:" + e.getStackTrace());
} finally {
// 释放连接
postMethod.releaseConnection();
httpClient.getHttpConnectionManager().closeIdleConnections(0);
log.info("after close httpClient.getState()="
+ httpClient.getState());
}

return response;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐