Apache HttpClient 进程 HttpResponse

Apache HttpClient process HttpResponse

我正在尝试使用 Google 的 URL 缩短器 API。

我得到的响应应该是这样的:

200

cache-control:  no-cache, no-store, max-age=0, must-revalidate
content-encoding:  gzip
content-length:  106
content-type:  application/json; charset=UTF-8
date:  Thu, 07 Dec 2017 23:39:07 GMT
etag:  "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
expires:  Mon, 01 Jan 1990 00:00:00 GMT
pragma:  no-cache
server:  GSE
vary:  Origin, X-Origin

{
 "kind": "urlshortener#url",
 "id": "[SHORTENED URL HERE]",
 "longUrl": "http://www.facebook.com/"
}

我希望能够处理返回的 Json,以便我可以访问 'id' 字段并获得缩短的 URL。

但是我得到的回复是这样的:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Date: Fri, 08 Dec 2017 10:10:37 GMT
ETag: "qQqhpr1RL6vGc3-0yacNoUjh_Uc/W5VD-15ZqaQDW9L-OELlMzo1ih4"
Vary: Origin
Vary: X-Origin
Content-Type: application/json; charset=UTF-8
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"
Transfer-Encoding: chunked 

如果有人能帮助我弄清楚如何访问 'id' Json 字段,以便我可以获得缩短的 URL.[=13,我将不胜感激=]

我的代码是:

HttpPost httppost = new HttpPost("https://www.googleapis.com/urlshortener/v1/url?key=[MY_API_KEY]);
String jsondata = "{\"longUrl\": \"http://www.facebook.com/\"}";

StringEntity jsonparam = new StringEntity(jsondata);
jsonparam.setContentType("application/json;charset=utf-8");
jsonparam.setChunked(false);

httppost.addHeader("content-type", "application/json;charset=UTF-8");
httppost.setEntity(jsonparam);

HttpClient httpclient = HttpClientBuilder.create().build();
HttpResponse httpresponse = httpclient.execute(httppost);

Header[] headers = httpresponse.getAllHeaders();
for (Header header : headers) {
    System.out.println(header);
}

要阅读正文内容,您应该执行以下操作

try(InputStream content = httpresponse.getEntity().getContent())
        {
            //With apache
            String jsonResponse = IOUtils.toString(content, "UTF-8");
            System.out.println(jsonResponse);
        } catch (UnsupportedOperationException | IOException e) 
        {
            //Do something here, e.g. LOG
        }

如果您使用的是 apache IOUtil,您将需要以下依赖项 https://mvnrepository.com/artifact/commons-io/commons-io

最好验证返回的状态代码以确保包含内容,例如200.

可以找到将 InputStream 转换为 String 的其他方法 here

加载到字符串后,您可以使用 GSON or using help from here 等库。通过转换为 Java 对象,您可以更轻松地检索 id 字段。