简体   繁体   English

从我的 android 工作室 java 应用程序上的 node.js 服务器获取 txt 文件

[英]Getting a txt file from a node.js server on my android studio java application

I am making an app on android studio using java and i want to make a website that you can edit txt files on.我正在使用 java 在 android 工作室制作应用程序,我想制作一个可以编辑 txt 文件的网站。 I want the android app to connect to the web server and retrieve these files.我希望 android 应用程序连接到 web 服务器并检索这些文件。 I just don't understand how to connect the two together.我只是不明白如何将两者联系在一起。 like how do i get a txt file from my node.js server to my android app.就像我如何从我的 node.js 服务器获取一个 txt 文件到我的 android 应用程序一样。 my initial thought would like to be a HTTP request to the server but i have no clue how to even start coding that.我最初的想法是向服务器发出 HTTP 请求,但我什至不知道如何开始编码。 Any help would be very appreciated Thank you in advance任何帮助将不胜感激提前谢谢您

JAVA JAVA

public class MainActivity extends AppCompatActivity {

private static final String SERVER = "http://10.0.2.2:3000/";

private TextView tvServerResponse;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvServerResponse = findViewById(R.id.textView);
    Button contactServerButton = findViewById(R.id.button);
    contactServerButton.setOnClickListener(onButtonClickListener);
}

View.OnClickListener onButtonClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        HttpGetRequest request = new HttpGetRequest();
        request.execute();
    }
};

public class HttpGetRequest extends AsyncTask<Void, Void, String> {

    static final String REQUEST_METHOD = "GET";
    static final int READ_TIMEOUT = 15000;
    static final int CONNECTION_TIMEOUT = 15000;

    @Override
    protected String doInBackground(Void... params){
        String result;
        String inputLine;

        try {
            // connect to the server
            URL myUrl = new URL(SERVER);
            HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();
            connection.setRequestMethod(REQUEST_METHOD);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.connect();

            // get the string from the input stream
            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();
            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }
            reader.close();
            streamReader.close();
            result = stringBuilder.toString();

        } catch(IOException e) {
            e.printStackTrace();
            result = "error";
        }

        return result;
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        tvServerResponse.setText(result);
    }
}

} }

JS: JS:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});`

Ive got this code but it throws the catch in the java code from the line connection.connect()我得到了这个代码,但它从行 connection.connect() 中抛出了 java 代码中的问题

i assume it cant connect to the server but i dont understand why我认为它无法连接到服务器,但我不明白为什么

You can use a very popular HTTP library called OkHttp ( https://github.com/square/okhttp )您可以使用一个非常流行的 HTTP 库,称为 OkHttp ( https://github.com/square/okhttp )

I wrote this snippet of code so you can adapt it in your application:我编写了这段代码,以便您可以在您的应用程序中调整它:

Java: Java:

  public void downloadTxt(String url) {
    Request request = new Request.Builder()
        .url(url)
        .build();
    OkHttpClient client = new OkHttpClient();
    client
        .newCall(request)
        .enqueue(new Callback() {
          @Override
          public void onFailure(@NotNull Call call, @NotNull IOException e) {
              //error reaching your site
              e.printStackTrace();
          }

          @Override
          public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if(response.isSuccessful()) {
              System.out.println(response.body().string());
            } else {
              System.out.println("Error with code: "+response.code());
            }
          }
        });
  }

Kotlin: Kotlin:

    fun downloadTxt(url: String) {
        val request: Request = Request.Builder()
            .url(url)
            .build()
        val client = OkHttpClient()
        client
            .newCall(request)
            .enqueue(object : Callback() {
                fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                fun onResponse(call: Call, response: Response) {
                    if (response.isSuccessful()) {
                        println(response.body().string())
                    } else {
                        println("Error with code: ${response.code()}")
                    }
                }
            })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM