3

继续得到这个:

V/RESPONSE(13605):  {
V/RESPONSE(13605):  "error": {
V/RESPONSE(13605):   "errors": [
V/RESPONSE(13605):    {
V/RESPONSE(13605):     "domain": "global",
V/RESPONSE(13605):     "reason": "parseError",
V/RESPONSE(13605):     "message": "This API does not support parsing form-encoded input."
V/RESPONSE(13605):    }
V/RESPONSE(13605):   ],
V/RESPONSE(13605):   "code": 400,
V/RESPONSE(13605):   "message": "This API does not support parsing form-encoded input."
V/RESPONSE(13605):  }
V/RESPONSE(13605): }

使用此代码:

String apiKey = "blahblahblah";
String address="https://www.googleapis.com/urlshortener/v1/url";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("key", apiKey));
pairs.add(new BasicNameValuePair("longUrl", original));

try {
    post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

try {
    org.apache.http.HttpResponse response = client.execute(post);
    String responseBody = EntityUtils.toString(response.getEntity());
    Log.v("RESPONSE"," "+responseBody);
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    tinyUrl="Protocol Error";
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    tinyUrl="IO Error";
}

我不确定如何格式化。有任何想法吗?

我尝试删除UrlEncodedFormEntity,但这当然行不通。

4

2 回答 2

4

您需要将数据作为 json 发送,而不是像您尝试做的那样进行编码。

看看这里的文档。

将实体更改为 StringEntity,如下所示:

post.setEntity(new StringEntity("{\"longUrl\": \"http://www.google.com/\"}"));

还要设置请求的内容类型:

post.setHeader("Content-Type", "application/json");
于 2011-05-18T23:44:58.590 回答
1

还可以考虑使用我制作的库,它提供了一个很好的界面来使用 Goo.gl 服务缩短您的网址。

它支持 api 密钥并且非常易于使用:

GoogleShortenerPerformer shortener = new GoogleShortenerPerformer(new OkHttpClient());

String longUrl = "http://www.andreabaccega.com/";

GooglShortenerResult result = shortener.shortenUrl(
    new GooglShortenerRequestBuilder()
        .buildRequest(longUrl)
    );
if ( Status.SUCCESS.equals(result.getStatus()) ) {
    // all ok result.getShortenedUrl() contains the shortened url!
}

看看这里的 github 存储库,其中包含更多信息:)

于 2014-10-30T22:12:27.087 回答