문제

계속이 옵션을 유지하십시오 :

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