2015-03-24 3 views

ответ

0

Вы можете использовать этот код, чтобы получить ответ:

String textFileUrl = "http://10.0.2.2:8080/myserver/arquivo.txt" 
String textFileText; 


    Request httpRequest = new Request(); 
      httpRequest.execute(textFileUrl); 
      try { 
       textFileText = httpRequest.get(5000, TimeUnit.MILLISECONDS); 
      } catch (InterruptedException | ExecutionException | TimeoutException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
System.out.println("The online text file contains: " + textFileText); 

TextView textView = (TextView)findViewById(R.id.textview); 
textView.setText(textFileText); 

Создать новый файл с именем Request.java:

import java.io.ByteArrayOutputStream; 
import java.io.IOException; 

import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.StatusLine; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.os.AsyncTask; 


public class Request extends AsyncTask<String, String, String>{ 

    HttpResponse response = null; 

    public Request(){ 


    } 


    @Override 
    protected String doInBackground(String... uri) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     String responseString = null; 
     try { 
      response = httpclient.execute(new HttpGet(uri[0])); 
      StatusLine statusLine = response.getStatusLine(); 
      if(statusLine.getStatusCode() == HttpStatus.SC_OK){ 
       ByteArrayOutputStream out = new ByteArrayOutputStream(); 
       response.getEntity().writeTo(out); 
       out.close(); 
       responseString = out.toString(); 

      } else{ 
       //Closes the connection. 
       response.getEntity().getContent().close(); 
       throw new IOException(statusLine.getReasonPhrase()); 
      } 
     } catch (ClientProtocolException e) { 
      //TODO Handle problems.. 
     } catch (IOException e) { 
      //TODO Handle problems.. 
     } 
     return responseString; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     //Do anything with response.. 
    } 
} 
+0

У меня возникли проблемы на: @Override охраняемого недействительный onPostExecute (Строковый результат) { super.onPostExecute (результат); TextView text = (TextView) findviewById (R.id.textView); text.setText (response); } –

+0

@ClaudioCastro Проверьте ответ. Я добавил новую строку в нижней части первой части кода, которая помещает полученный текст в текстовое представление. Убедитесь, что у вас есть разрешение INTERNET, указанное в манифесте Android! – tim687

+0

спасибо! теперь, в моем случае, «текст», который я получил, - это число. Как я могу использовать это как переменную? –