I Couldn't get any IP when I run the following method:
System.out.println("IP: " +getIpAddress());
public String getIpAddress()
{
String ip = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
//HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
HttpGet httpget = new HttpGet("http://agentgatech.appspot.com/");
HttpResponse response;
System.out.println("IP: 1");
response = httpclient.execute(httpget);
System.out.println("IP: 2" +response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
entity.getContentLength();
String str = EntityUtils.toString(entity);
System.out.println("IP 3" +getApplicationContext() +str);
JSONObject json_data = new JSONObject(str);
ip = json_data.getString("ip");
System.out.println("IP 4" +getApplicationContext() +ip);
}
catch (Exception e)
{
}
return ip;
}
I have already added thw following to the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
I just got the following printed out!:
IP: 1
IP: null
Can any one tell me why? where is the wrong in this code?
Edit: Just for the others, the answer is by using thread as shown bellow:
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
// HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
HttpGet httpget = new HttpGet("http://agentgatech.appspot.com/");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
entity.getContentLength();
String str = EntityUtils.toString(entity);
System.out.println("External IP: " +str);
} catch (Exception e) {
e.printStackTrace();
}
}
});
To start it:
thread.start();