之前很多次用到过httpclient,尤其是在做接口对接的时候,今天在做接口对接的时候,发现了两个问题:1.HttpClient 对象的executeMethod 方法里面的参数是PostMethod 对象,执行这行代码的时候,有些情况下,执行到这段代码的时候所花费的时间比较长。
2.PostMethod 对象的getResponseBodyAsString 返回值是string的时候,当返回值过大的时候会给你警告:
警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
所以可以按警告的要求将采用getResponseBodyAsStream 方法来获取返回值,具体如下:
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while((str = reader.readLine())!=null){
stringBuffer.append(str);
}
String ts = stringBuffer.toString();
return ts。结束.
但是对于第一个问题我在网上找了好多资料,说是有的时候PostMethod 对象的值过大,导致client.executeMethod(post);这段代码执行时间过长,但是我在debug的过程中发现,其实post的大小都是差不多的,都是传了一个值,所以我现在还在想到底是什么原因,有知道的大神可以在这里分享下,大家一起来交流。
/**
* 发送http请求,以post方式
* @param url
* @return
* @throws IOException
* @throws HttpException
*/
public static String doPost(String url,String name,String responeJsonStr) throws IOException,HttpException{
//强制设置可信任证书
Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
if(StrUtil.isNotNull(name)){
NameValuePair[] param = {new NameValuePair(name,responeJsonStr)} ;
post.setRequestBody(param);
}else{
post.setRequestBody(responeJsonStr);
}
post.getParams().setContentCharset("utf-8");
//发送http请求
String respStr = "";
client.executeMethod(post);
respStr = post.getResponseBodyAsString();
return respStr;
}