Question

Continuez à recevoir ceci :

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

en utilisant ce 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";
}

Je ne sais pas comment formater cela.Des idées?

J'ai essayé de supprimer UrlEncodedFormEntity, mais bien sûr, cela ne fonctionnerait pas.

Était-ce utile?

La solution

Vous devez envoyer les données au format JSON, et non sous forme codée comme vous essayez de le faire.

Jetez un oeil à la documentation ici.

Changez l'entité pour qu'elle soit une StringEntity comme ceci :

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

Définissez également le type de contenu de la requête :

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

Autres conseils

Pensez également à utiliser une bibliothèque que j'ai créée et qui fournit une interface agréable pour raccourcir vos URL à l'aide du service Goo.gl.

Il prend en charge la clé API et est très simple à utiliser :

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

Jetez un oeil à dépôt github ici qui contient plus d'informations :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top