我已经写了这个简单的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
try{
response.close();
}
catch(NullPointerException e){
e.printStackTrace();
}
inside最终阻止。
尝试一下,而不要使用这么多的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);