zoukankan      html  css  js  c++  java
  • HttpClient(4.3.5)

    The simplest and the most convenient way to handle responses is by using the ResponseHandler interface, which includes the handleResponse(HttpResponse response) method. This method completely relieves the user from having to worry about connection management. When using a ResponseHandler, HttpClient will automatically take care of ensuring release of the connection back to the connection manager regardless whether the request execution succeeds or causes an exception.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/json");
    
    ResponseHandler<MyJsonObject> rh = new ResponseHandler<MyJsonObject>() {
    
        @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 = client.execute(httpget, rh);
  • 相关阅读:
    CF 1083 A. The Fair Nut and the Best Path
    2434: [Noi2011]阿狸的打字机
    HDU 6086 Rikka with String
    HDU 2825 Wireless Password
    异常处理与补充模块
    面向对象
    初始socket
    面向对象的进阶(组合和继承)
    初始面向对象
    python之其他模块的用法
  • 原文地址:https://www.cnblogs.com/huey/p/4523303.html
Copyright © 2011-2022 走看看