如何在 MainActivity.java 中发出简单的 HTTP 请求?(安卓工作室) [英] How can I make a simple HTTP request in MainActivity.java? (Android Studio)

查看:61
本文介绍了如何在 MainActivity.java 中发出简单的 HTTP 请求?(安卓工作室)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Android Studio, and I've spent a few hours trying to do a simple HTTP request in my MainActivity.java file, and tried multiple ways, and seen many web pages on the subject, yet cannot figure it out.

当我尝试 OkHttp 时,我收到关于无法在主线程上执行此操作的错误.现在我正在尝试这样做:

When I try OkHttp, I get a error about not being able to do it on the main thread. Now I'm trying to do it this way:

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 中的方法中执行它:

I put that method directly in MainActivity.java, and my click event executes it from another method that is also in MainActivity.java:

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

但现在没有崩溃,我可以看出在以BufferedReader"开头的行上抛出了异常,但 e.getMessage() 为空.

But right now there is no crash, and I can tell there is an exception thrown on the line that starts "BufferedReader", but e.getMessage() is blank.

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

I'm brand new to Android Studio and java, so please be kind and help me with this very basic problem. Eventually I will need to do post requests to the server, and it seems that OkHttp is the best way to go, but I'm not finding the "Hello World" of OkHttp in Android Studio documented anywhere online.

推荐答案

您不应该在主线程上发出网络请求.延迟是不可预测的,可能会冻结 UI.

You should not make network requests on the main thread. The delay is unpredictable and it could freeze the UI.

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

Android force this behaviour by throwing an exception if you use the HttpUrlConnection object from the main thread.

然后您应该在后台发出网络请求,然后在主线程上更新 UI.AsyncTask 类对于这个用例!

You should then make your network request in the background, and then update the UI on the main thread. The AsyncTask class can be very handy for this use case !

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

你是这样开始这个过程的:

And you start this process this way:

new GetUrlContentTask().execute(sUrl)

这篇关于如何在 MainActivity.java 中发出简单的 HTTP 请求?(安卓工作室)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆