GetExternalIPTask.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package de.tudarmstadt.informatik.hostage.commons;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.impl.client.DefaultHttpClient;
  7. import org.apache.http.util.EntityUtils;
  8. import org.json.JSONObject;
  9. import android.os.AsyncTask;
  10. /**
  11. * A {@link android.os.AsyncTask} that determines and returns the external IP address of the device.
  12. * Therefore it uses a given URL to get a JSON Object containing the external IP address.
  13. * @author Lars Pandikow
  14. *
  15. */
  16. public class GetExternalIPTask extends AsyncTask<String, Void, String> {
  17. @Override
  18. protected String doInBackground(String... url) {
  19. String ipAddress = null;
  20. try {
  21. HttpClient httpclient = new DefaultHttpClient();
  22. HttpGet httpget = new HttpGet(url[0]);
  23. HttpResponse response;
  24. response = httpclient.execute(httpget);
  25. HttpEntity entity = response.getEntity();
  26. entity.getContentLength();
  27. String str = EntityUtils.toString(entity);
  28. JSONObject json_data = new JSONObject(str);
  29. ipAddress = json_data.getString("ip");
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. return ipAddress;
  34. }
  35. }