在Android上有缩短URL的方法吗。我在Google Play服务库上注意到了一些东西(https://code.google.com/p/google-api-java-client/)
或者我应该使用HTTPPOST来获取新的URL?
提前感谢!
1º在Manifest中授予Internet权限。
2º在异步任务中使用此功能:
private final String GOOGLE_URL = "https://www.googleapis.com/urlshortener/v1/url";
public static String getShortUrl( String _url ){
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 5000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost request = new HttpPost(GOOGLE_URL);
request.setHeader("Content-type", "application/json");
request.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("longUrl", _url);
request.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = hc.execute(request);
if ( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK )
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
return out.toString();
}
else {
return null;
}
}
catch ( Exception e ) {
e.printStackTrace();
}
return null;
}