如何使用Google API Java客户端向Google Shortener API发送请求并解析JSON响应? [英] How to POST request to Google Shortener API with Google API Java Client and parse a JSON response?

查看:155
本文介绍了如何使用Google API Java客户端向Google Shortener API发送请求并解析JSON响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Google Shortener API 。我想使用google api java客户端库发布请求并解析JSON响应。

I want to use the Google Shortener API. I want to use the google api java client library to post a request and parse the JSON response.

接下来,我发布了我尝试过的代码:

Next, I post the code I have tried:

import java.io.IOException; 
import net.sf.json.JSONObject; 
import com.google.api.client.googleapis.GoogleHeaders; 
import com.google.api.client.googleapis.GoogleTransport; 
import com.google.api.client.googleapis.json.JsonCParser; 
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.JsonHttpContent; 
import com.google.api.client.util.GenericData;


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

    public static void main(String[] args) {    
        // 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 JsonCParser());
        // build the HTTP GET request and URL

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

        JsonHttpContent content = new JsonHttpContent();
        content.data = data;

        HttpRequest request = transport.buildPostRequest();
        request.content = content;
        request.setUrl(GOOGL_URL);
        HttpResponse response;
        try {
            JSONObject json = request.execute().parseAs(JSONObject.class);      
        } catch (IOException e) {           
           // TODO Auto-generated catch block                                
           e.printStackTrace();
        }
    } 
}

当我执行上面的代码时,我得到下一个输出:

When I execute the above code, I get the next output:

Exception in thread "main" java.lang.IllegalArgumentException: data key not found
    at com.google.api.client.googleapis.json.JsonCParser.parserForResponse(JsonCParser.java:77)
    at com.google.api.client.googleapis.json.JsonCParser.parse(JsonCParser.java:47)
    at com.google.api.client.http.HttpResponse.parseAs(HttpResponse.java:261)
    at GoogleShortener.main(GoogleShortener.java:43)

知道如何正确设置JsonCParser吗?

Any idea how to set the JsonCParser properly?

一开始我没有正确设置请求内容。正如@dwb所指出的,应该设置请求内容:

In the beginning I was not setting properly the request content. As pointed by @dwb, the request content should be set:

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

JsonHttpContent content = new JsonHttpContent();
content.data = data;

request.content = content;

如果你没有正确设置内容,你将收到下一个错误

If you do not set the content properly, you will get the next error


com.google.api.client.http.HttpResponseException:
411
com.google.api.client.http所需的长度。 HttpRequest.execute(HttpRequest.java:209)
at
GoogleShortener.main(GoogleShortener.java:32)

com.google.api.client.http.HttpResponseException: 411 Length Required at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:209) at GoogleShortener.main(GoogleShortener.java:32)


推荐答案

您需要将JSON内容添加到请求正文中,如下所示:

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;

对于响应,请尝试使用JsonHttpParser而不是JsonCParser。您需要创建GenericJson的子类,其中包含对要检索的每个JSON属性都带有@Key批注的字段。您可以使用response.parseAsString()来查看所有可用的属性。

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;
    }
}

这篇关于如何使用Google API Java客户端向Google Shortener API发送请求并解析JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆