How to POST request to Google Shortener API with Google API Java Client and parse a JSON response?

北城余情 提交于 2019-12-01 00:31:47

You need to add JSON content to the request body like this:

GenericData data = new GenericData();
data.put("longUrl", "http://www.google.com/");
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;

For the response, try using the JsonHttpParser instead of JsonCParser. You'll need to create a subclass of GenericJson that contains fields with a @Key annotation for every JSON property you want to retrieve. You can use response.parseAsString() to see all of the properties available.

Here's a full working example:

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
import com.google.api.client.util.Key;


public class Shortener {

    public static final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // setup up the HTTP transport
        HttpTransport transport = GoogleTransport.create();
        // add default headers
        GoogleHeaders defaultHeaders = new GoogleHeaders();
        transport.defaultHeaders = defaultHeaders;
        transport.defaultHeaders.put("Content-Type", "application/json");
        transport.addParser(new JsonHttpParser());

        // build the HTTP GET request and URL
        HttpRequest request = transport.buildPostRequest();
        request.setUrl(GOOGL_URL);
        GenericData data = new GenericData();
        data.put("longUrl", "http://www.google.com/");
        JsonHttpContent content = new JsonHttpContent();
        content.data = data;
        request.content = content;

        HttpResponse response = request.execute();
        Result result = response.parseAs(Result.class);

        System.out.println(result.shortUrl);
    }

    public static class Result extends GenericJson {        
        @Key("id")
        public String shortUrl;
    }
}

The code given by dwb is correct but it is using deprecated methods of the google client api.

Implementation with current library support is as follows :

import java.util.HashMap;
import java.util.Map;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.GenericJson;

import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;

public class ShortenUrl {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {

        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        HttpHeaders headers = new HttpHeaders();
        JsonObjectParser parser = new JsonObjectParser(new JacksonFactory());
        GenericUrl url = new GenericUrl("https://www.googleapis.com/urlshortener/v1/url");

        Map<String, String> json = new HashMap<String, String>();
        json.put("longUrl", "http://www.google.com/");

        final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);

        HttpRequest request = httpTransport.createRequestFactory().buildPostRequest(url, content);

        try {

            HttpResponse response = request.execute();
            Result result = response.parseAs(Result.class);
            System.out.println(result.shortUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static class Result extends GenericJson {
        @Key("id")
        public String shortUrl;
    }

}

Note : You should use your Oauth 2.0 credentials to use google api services.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!