如果你去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