当我运行以下方法时,我无法获得任何IP:
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;
}
我已经将以下内容添加到清单文件中:
<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" />
我刚打印出以下内容!:
IP: 1
IP: null
任何人都可以告诉我为什么吗?这段代码在哪里错了?
编辑: 仅针对其他人,答案是使用如下所示的线程:
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();
}
}
});
开始吧:
thread.start();