首先在 google 控制台上创建一个项目并启用 url shortner api 并获取 api 密钥并使用以下 Asynctask 来获取缩短的 url。
public class newShortAsync extends AsyncTask<Void,Void,String> {
String longUrl="http://stackoverflow.com/questions/18372672/how-do-i-use-the-google-url-shortener-api-on-android/20406915";
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
System.out.println("JSON RESP:" + s);
String response=s;
try {
JSONObject jsonObject=new JSONObject(response);
id=jsonObject.getString("id");
System.out.println("ID:"+id);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... params) {
BufferedReader reader;
StringBuffer buffer;
String res=null;
String json = "{\"longUrl\": \""+longUrl+"\"}";
try {
URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?key=YOUR_API_KEY");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(40000);
con.setConnectTimeout(40000);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(json);
writer.flush();
writer.close();
os.close();
int status=con.getResponseCode();
InputStream inputStream;
if(status==HttpURLConnection.HTTP_OK)
inputStream=con.getInputStream();
else
inputStream = con.getErrorStream();
reader= new BufferedReader(new InputStreamReader(inputStream));
buffer= new StringBuffer();
String line="";
while((line=reader.readLine())!=null)
{
buffer.append(line);
}
res= buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
然后只需执行此异步任务,您将获得一个 json 响应,其中 id 存在,只不过是缩短的 Url。