如果你去http://www.elven.ee/ip/ - 你可以看到它给出了IP。如果刷新,它会给出不同的端口。从互联网上获取文本
我怎样才能把这个IP到android中?我不知道如何让它每隔5秒更新一次,但现在我想知道如何将它放入我的手机中。我想把它显示为TextView :)。
如果你去http://www.elven.ee/ip/ - 你可以看到它给出了IP。如果刷新,它会给出不同的端口。从互联网上获取文本
我怎样才能把这个IP到android中?我不知道如何让它每隔5秒更新一次,但现在我想知道如何将它放入我的手机中。我想把它显示为TextView :)。
@mopsled解决方案并没有为我工作,所以这里是我的:
public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
String ip = "";
final DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://www.elven.ee/ip/");
try {
final HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
ip = getString(response);
}
} catch (final ClientProtocolException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
tv.setText(ip);
}
private static String getString(HttpResponse response) {
final HttpEntity retEntity = response.getEntity();
if (retEntity != null) {
InputStream instream = null;
try {
instream = retEntity.getContent();
} catch (final IllegalStateException ise) {
ise.printStackTrace();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
final String result = convertStreamToString(instream);
return result;
} else {
return "";
}
}
private static String convertStreamToString(final InputStream is) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (final IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
return sb.toString().trim();
}
}
编辑:固定码
尝试HTTPURLConnection(一个例子found here的简化版本):
StringBuilder content = new StringBuilder();
try {
URL url = new URL("http://www.elven.ee/ip/");
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
String myIp = content.toString();
对我来说它总是** IP **。每次调用后,只有';'后面的数字发生变化,但这不是** IP **(也许是端口号?)的一部分 –
噢,是的,这就是我的意思,端口变化:)。我的错。现在我只需要找出我可以做什么循环:(。 – Elven