3

我正在尝试在我的 android 应用程序中创建对 Google Shortener Api 的 POST 请求。但它返回带有代码 400 的 Parse 错误消息。这是我的代码......我错过了什么吗?

final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url";
String tinyUrl = null;
final Gson gson = new Gson();

try
{
    InputStream in;
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    JSONObject json = new JSONObject();
    HttpPost post = new HttpPost(GOOGL_URL);
    json.put("key", "my_key");
    json.put("longUrl", longUrl);
    post.setHeader("json", json.toString());
    StringEntity se = new StringEntity(json.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                                          "application/json"));
    post.setEntity(se);

    response = client.execute(post);
    in = response.getEntity().getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    StringBuilder resultString = new StringBuilder();
    String lineGet;

    while ((lineGet = br.readLine()) != null) {
        resultString.append(lineGet);
    }
    if (Common.DEBUG) {
        Log.d(TAG, "Request string : " + json.toString());
        Log.d(TAG, "Response string : " + resultString);
    }

    GooGlResult result = gson.fromJson(resultString.toString(),
                                       GooGlResult.class);

    return result.getId();
} 
catch (Exception ex) {
    System.out.println("UrlShortener "+ex);
    return longUrl;
}   

提前致谢..

4

1 回答 1

0

1)

final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key={API_KEY}";

2)

json.put("longUrl", longUrl);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
StringEntity se = new StringEntity(json.toString());
post.setEntity(se);
于 2014-01-10T10:38:15.007 回答