设为首页 加入收藏

TOP

Httpclient4.4之原理(请求执行)(三)
2015-07-16 12:56:20 来源: 作者: 【 】 浏览:43
Tags:Httpclient4.4 原理 请求 执行
ntentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true); //设置为分块编码
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);
?


8. response处理


处理response最简单,最方便的方式是使用ResponseHandler接口,它包含handleResponse(HttpResponse respnse)方法。这种方法让用户完全不用担心连接的管理。使用ResponseHandler时,HttpClient将自动释放连接并把连接放回连接管理器中,不论请求执行成功还是失败。示例:
?
package httpclienttest;
?
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
?
public class T14 {
? ? public static void main(String[] args) {
? ? ? ? CloseableHttpClient httpclient = HttpClients.createDefault();
? ? ? ? HttpGet httpget = new HttpGet("http://localhost/json");
? ? ? ? ResponseHandler rh = new ResponseHandler() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public JsonObject handleResponse(final HttpResponse response)throws IOException {
? ? ? ? ? ? ? ? StatusLine statusLine = response.getStatusLine();
? ? ? ? ? ? ? ? HttpEntity entity = response.getEntity();
? ? ? ? ? ? ? ? if (statusLine.getStatusCode() >= 300) {
? ? ? ? ? ? ? ? ? ? throw new HttpResponseException(statusLine.getStatusCode(),
? ? ? ? ? ? ? ? ? ? ? ? ? ? statusLine.getReasonPhrase());
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (entity == null) {
? ? ? ? ? ? ? ? ? ? throw new ClientProtocolException("Response contains no content");
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? Gson gson = new GsonBuilder().create();
? ? ? ? ? ? ? ? ContentType contentType = ContentType.getOrDefault(entity);
? ? ? ? ? ? ? ? Charset charset = contentType.getCharset();
? ? ? ? ? ? ? ? Reader reader = new InputStreamReader(entity.getContent(), charset);
? ? ? ? ? ? ? ? return gson.fromJson(reader, MyJsonObject.class);
? ? ? ? ? ? }
? ? ? ? };
? ? ? ? MyJsonObject myjson = httpclient.execute(httpget, rh);
? ? }
}


首页 上一页 1 2 3 4 5 下一页 尾页 3/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java8之lambda表达式(变量作用域.. 下一篇详解Linux平台芯片烧写流程

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: