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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38593371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:26:49  来源:igfitidea点击:

How can I make a simple HTTP request in MainActivity.java? (Android Studio)

javahttpandroid-studiookhttp3

提问by Brian Gottier

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.

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

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:

当我尝试 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;
}

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

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

try {
    String str = getUrlContent("https://example.com/WAN_IP.php");
    displayMessage(str);
}
catch(Exception e){
    displayMessage(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.

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

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.

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

采纳答案by Nicolas Dusart

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

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

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

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

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

然后,您应该在后台发出网络请求,然后在主线程上更新 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);
     }
 }

And you start this process this way:

你这样开始这个过程:

new GetUrlContentTask().execute(sUrl)

回答by Chayon Ahmed

if your using okhttp then call aysnc try bellow code

如果您使用 okhttp 然后调用 aysnc 尝试波纹管代码

 private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://publicobject.com/helloworld.txt")
        .build();
     client.setConnectTimeout(15, TimeUnit.SECONDS);
    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Headers responseHeaders = response.headers();
        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
          Log.e(responseHeaders.name(i) , responseHeaders.value(i));
        }

       Log.e("response",response.body().string());
      }
    });
  }

回答by Predator_Shek

You can use dependency for making HTTP requests or HTTPS request,Use OkHttp

您可以使用依赖来发出 HTTP 请求或 HTTPS 请求,使用 OkHttp

Visit :https://square.github.io/okhttp

访问:https: //square.github.io/okhttp

 OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  try (Response response = client.newCall(request).execute()) {
    return response.body().string();
  }
}