Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
goo.gl URL shortener for Android
import android.os.AsyncTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by piero on 2/17/15.
* Usage
* new URLShortener().getShortUrl(url, new URLShortener.RequestEndListner() {
* @Override
* public void onRequestEnd(String shortUrl) {
* //use shortUrl for your purpose
* }
*
* @Override
* public void onRequestException() {
* //something went wrong
* }
* });
*/
public class URLShortener {
final String address = "https://www.googleapis.com/urlshortener/v1/url";
public void getShortUrl(String longUrl, RequestEndListner requestEndListner) {
new UrlShortnerRequest().execute(longUrl, requestEndListner);
}
public interface RequestEndListner {
public void onRequestEnd(String url);
public void onRequestException();
}
private class UrlShortnerRequest extends AsyncTask<Object, Void, JSONObject> {
RequestEndListner listeRequestEndListner;
@Override
protected JSONObject doInBackground(Object... params) {
try {
listeRequestEndListner = (RequestEndListner) params[1];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(address);
JSONObject json = new JSONObject();
json.put("longUrl", params[0]);
httpPost.setEntity(new StringEntity(json.toString()));
httpPost.setHeader("Content-Type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return jsonStream2Object(httpEntity.getContent());
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(JSONObject result) {
if (result == null) {
listeRequestEndListner.onRequestException();
} else {
try {
listeRequestEndListner.onRequestEnd(result.getString("id"));
} catch (JSONException e) {
listeRequestEndListner.onRequestException();
e.printStackTrace();
}
}
}
private String stream2String(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream), 8);
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private JSONObject jsonStream2Object(InputStream inputStream) throws JSONException {
return new JSONObject(stream2String(inputStream));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment