简体   繁体   中英

get request is not working on android device however it's working on my pc

I've wrote this simple get request

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

when i tested it on my pc it worked just fine however when i tested it on my mobile it gave me the following exception

java.lang.NullPointerException: Attempt to invoke virtual method 'void okhttp3.Response.close()' on a null object reference
  try{
      response.close();
  }
  catch(NullPointerException e){
   e.printStackTrace();
  }

inside finally block.

Try this out rather then using this many 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();
  }

Then just call above method and pass your url whenever you need.

 String response =doGetRequest(yourUrl);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM