httpclient请求
2015-07-06 10:27
716 查看
之前很多次用到过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; }
相关文章推荐
- velocity http请求400错误HTTP Status 400 The request sent by the client was syntactically incorrect
- AsyncHttpClient请求网络数据小节!
- HttpClient(get/post)请求封装成工具类
- HttpClient get请求在HttpResponse中无法获得Location的问题
- httpcomponents-client-4.3.5实现http的post请求和get请求方法
- Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子
- httpclient post请求返回301解决方案
- HttpClient4.x进行Get/Post请求并使用ResponseHandler处理响应
- httpclient3.1发送https 的post请求,带参
- 【Angular】angular-HttpClient 与服务器通讯 Get Post Put Delete Http 拦截器 请求讲解
- 【Angular】angular-HttpClient 与服务器通讯 Get Post Put Delete Http 拦截器 请求讲解
- httpclient3.1下的请求头和params
- java apache commons HttpClient发送get和post请求的学习整理
- Http请求连接池 - HttpClient 连接池
- 使用Httpclient向百度翻译提交POST请求 接受返回的JSON字符串 实现翻译功能(2)----Httpclient使用详解
- httpClient通过代理(Http Proxy)进行请求
- Android Asynchronous Http Client-Android异步网络请求客户端接口
- HttpClient发送post请求
- Httpclient发送POST请求
- HttpClient请求返回JSON、图片