Android - 文本文件 - 网络服务器

Android - textfile- webserver

我正在做一个 android 应用程序,我想从服务器 (http://10.0.2.2:8080/myserver/arquivo.txt) 读取一个文本文件并在我的应用程序中显示该文本。 我不知道该怎么做。 有人可以帮忙吗?

您可以使用此代码获取响应:

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..
    }
}