【问题标题】:Getting a txt file from a node.js server on my android studio java application从我的 android studio java 应用程序上的 node.js 服务器获取 txt 文件
【发布时间】:2021-05-26 16:51:28
【问题描述】:

我正在使用 java 在 android studio 上制作一个应用程序,我想制作一个可以编辑 txt 文件的网站。我希望 android 应用程序连接到 Web 服务器并检索这些文件。我只是不明白如何将两者联系在一起。就像我如何从我的 node.js 服务器获取一个 txt 文件到我的 android 应用程序一样。我最初的想法想成为对服务器的 HTTP 请求,但我不知道如何开始编码。 任何帮助将不胜感激 提前谢谢你

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:

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}/`);
});`

我得到了这段代码,但它从行 connection.connect() 中抛出了 java 代码中的问题

我认为它无法连接到服务器,但我不明白为什么

【问题讨论】:

    标签: javascript java android node.js


    【解决方案1】:

    您可以使用一个非常流行的 HTTP 库,称为 OkHttp (https://github.com/square/okhttp)

    我编写了这段 sn-p 代码,以便您可以在您的应用程序中调整它:

    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());
                }
              }
            });
      }
    

    科特林:

        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()}")
                        }
                    }
                })
        }
    

    【讨论】:

    • 我正试图让应用程序立即连接到服务器,然后调整来自服务器的响应,此时我刚刚得到它返回 Hello World。我已经编辑了我的问题以包含我正在尝试使用的代码
    • 我已尝试实现此功能,但似乎仍然无法连接,甚至无法连接到https://reqres.in/api/users?page=2//。除了在android清单中添加:&lt;uses-permission android:name="android.permission.INTERNET"/&gt;之外还有什么其他的吗?
    • 为什么要在网址末尾添加双斜杠?这是reqres.in/api/users?page=2,它有效。可能是设备连接有问题?
    • 这就是我的想法,如果没有//,它就无法工作,我不太清楚如何解决设备上的连接问题
    • 请与全班同学分享一个要点,以便我们看到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多