获取请求在android设备上不起作用,但是在我的PC上起作用

问题描述 投票:0回答:2

我已经写了这个简单的get请求

OkHttpClient httpClient = new OkHttpClient();
StringBuilder url = new StringBuilder(serverURL);

String result = "init";
if(params!=null && params.size()!=0){
    url = url.append("?"+prepareParam(params));
}
Request request = new Request.Builder().url(url.toString()).build();
Response response = null;
try {
response = httpClient.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
    e.printStackTrace();
}
catch (Exception e){
    e.printStackTrace();
}finally {
    response.close();
}

当我在我的电脑上对其进行测试时,它工作正常,但是当我在手机上对其进行测试时,它给了我以下异常

java.lang.NullPointerException: Attempt to invoke virtual method 'void okhttp3.Response.close()' on a null object reference
java android okhttp
2个回答
1
投票
  try{
      response.close();
  }
  catch(NullPointerException e){
   e.printStackTrace();
  }

inside最终阻止。


0
投票

尝试一下,而不要使用这么多的try catch。

  OkHttpClient client = new OkHttpClient();
  String doGetRequest(String url) throws IOException {
    Request request = new Request.Builder()
        .url(url)
        .build();
    Response response = client.newCall(request).execute();
    return response.body().string();
  }

然后只需调用上述方法,并在需要时传递您的网址。

 String response =doGetRequest(yourUrl);
© www.soinside.com 2019 - 2024. All rights reserved.