2

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

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

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

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

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 吗?

错误路径

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

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

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

request.content = content;

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

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

4

2 回答 2

6

您需要像这样将 JSON 内容添加到请求正文中:

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

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

这是一个完整的工作示例:

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;
    }
}
于 2011-01-18T16:40:00.810 回答
1

dwb 给出的代码是正确的,但它使用的是谷歌客户端 API 的弃用方法。

当前库支持的实现如下:

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

}

注意:您应该使用您的 Oauth 2.0 凭据来使用 google api 服务。

于 2016-08-22T12:33:37.847 回答