[英]get request is not working on android device however it's working on my pc
我寫了這個簡單的獲取請求
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();
}
里面 finally 塊。
試試這個,而不是使用這么多 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.