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

后端 未结 3 1943
無奈伤痛
無奈伤痛 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: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());
          }
        });
      }
    

提交回复
热议问题