java - 如何在 MainActivity.java 中发出简单的 HTTP 请求? (安卓工作室)

标签 java http android-studio okhttp

我正在使用 Android Studio,我花了几个小时尝试在我的 MainActivity.java 文件中执行一个简单的 HTTP 请求,并尝试了多种方法,并且看到了很多关于该主题的网页,但无法理解出。

当我尝试 OkHttp 时,出现无法在主线程上执行的错误。现在我正在尝试这样做:

public static String getUrlContent(String sUrl) throws Exception {
    URL url = new URL(sUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    connection.connect();
    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String content = "", line;
    while ((line = rd.readLine()) != null) {
        content += line + "\n";
    }
    return content;
}

我将该方法直接放在 MainActivity.java 中,我的点击事件从另一个也在 MainActivity.java 中的方法执行它:

try {
    String str = getUrlContent("https://example.com/WAN_IP.php");
    displayMessage(str);
}
catch(Exception e){
    displayMessage(e.getMessage());
}

但现在没有崩溃,我可以看出在开始“BufferedReader”的行上抛出了一个异常,但是 e.getMessage() 是空白的。

我是 Android Studio 和 java 的新手,所以请友好地帮助我解决这个非常基本的问题。最终我需要向服务器发送请求,OkHttp 似乎是最好的方式,但我没有在网上任何地方找到 Android Studio 中 OkHttp 的“Hello World”记录。

最佳答案

你不应该在主线程上进行网络请求。延迟是不可预测的,它可能会卡住 UI。

如果您从主线程使用 HttpUrlConnection 对象,Android 会通过抛出异常来强制执行此行为。

然后您应该在后台发出网络请求,然后在主线程上更新 UI。 AsyncTask类对于这个用例来说非常方便!

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
     protected String doInBackground(String... urls) {
        URL url = new URL(urls[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();
        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String content = "", line;
        while ((line = rd.readLine()) != null) {
            content += line + "\n";
        }
        return content;
     }

     protected void onProgressUpdate(Integer... progress) {
     }

     protected void onPostExecute(String result) {
         // this is executed on the main thread after the process is over
         // update your UI here
         displayMessage(result);
     }
 }

然后您以这种方式开始此过程:

new GetUrlContentTask().execute(sUrl)

关于java - 如何在 MainActivity.java 中发出简单的 HTTP 请求? (安卓工作室),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593371/

相关文章:

node.js - node http 和 express 监听区别

android - fragment 之间通过接口(interface)进行通信

Java 8 LocalDateTime 在使用 00 秒(如 "2018-07-06 00:00:00")解析日期字符串值时丢弃 00 秒值

java - 构建 Spark 项目方法

php - PHP(使用 Apache 或 Nginx)可以在 POST 请求完成之前检查 HTTP header 吗?

c# - 是否可以通过http将数据从客户端传输到服务器?

android-studio - 如何检测具有较新版本的 Android Gradle 依赖项?

android - 触发 Android Studio 以显示方法签名?

java - 如果组件对于方法而言是本地的,则从其自己的监听器引用该组件

java - Onclick Recycler View 中的按钮不起作用