3

Keep getting this:

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): }

using this code:

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

I'm not sure how to format this. Any ideas?

I tried removing UrlEncodedFormEntity, but of course that wouldn't work.

Oscar Mederos
  • 29,016
  • 22
  • 84
  • 124
jj.
  • 343
  • 1
  • 7
  • 20

2 Answers2

4

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");
aromero
  • 25,681
  • 6
  • 57
  • 79
1

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 :)

Andrea Baccega
  • 27,211
  • 13
  • 45
  • 46