Получение текста из интернета - PullRequest
0 голосов
/ 11 августа 2011

Если вы перейдете на http://www.elven.ee/ip/ - вы можете увидеть, что это дает IP. Если вы обновите, это даст другой порт.

Как я могу получить этот IP в Android? Я не знаю, как заставить его также обновляться примерно каждые 5 секунд, но сейчас я хочу знать, как я могу получить его в свой телефон. Я хочу отобразить его как TextView:).

Ответы [ 2 ]

1 голос
/ 11 августа 2011

@ решение 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();
}
}
0 голосов
/ 11 августа 2011

РЕДАКТИРОВАТЬ : Фиксированный код

Попробуйте HTTPURLConnection (упрощенная версия примера найдена здесь ):

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();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...