继续实现:

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,但当然是不起作用的。

有帮助吗?

解决方案

You need to send the data as json, not form encoded as you are trying to do.

Take a look at the documentation here.

Change the entity to be a StringEntity like this:

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

Also set the content type of the request:

post.setHeader("Content-Type", "application/json");

其他提示

Also consider using a library I made that provide a nice interface to shorten your urls using Goo.gl service.

It supports the api key and is very easy to use:

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

Take a look at the github repo here which contains further infos :)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top