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

后端 未结 3 1923
無奈伤痛
無奈伤痛 2020-12-30 15:03

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 t

相关标签:
3条回答
  • 2020-12-30 15:49

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

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

    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)
    
    0 讨论(0)
  • 2020-12-30 15:56

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

    Visit :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();
      }
    }
    
    0 讨论(0)
  • 2020-12-30 15:57

    if your using okhttp then call aysnc try bellow code

     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());
          }
        });
      }
    
    0 讨论(0)
提交回复
热议问题