I'm trying to use Google's URL shortener API.
The response I get should look like:
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/"
}
I want to be able to process the Json returned so that I can access the 'id' field and get the shortened URL.
However the response that I am getting looks like this:
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
I would appreciate it if someone could help me to figure out how to get access to the 'id' Json field so that I can get the shortened URL.
My code for this is:
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);
}
To read the body content you should do the following
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
}
If you are using apache IOUtil you will need the following dependency https://mvnrepository.com/artifact/commons-io/commons-io
It is good practice to validate the returned status code to ensure that content is included e.g. 200.
Other methods of transforming the InputStream to a String can be found here.
Once loaded to a String you can use libraries such as GSON or using help from here. By converting to a Java object you can more easily retrieve the id field.