简体   繁体   English

获取请求在 android 设备上不起作用,但它在我的电脑上运行

[英]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.里面 finally 块。

Try this out rather then using this many try catch.试试这个,而不是使用这么多 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Android 设备监视器在我的 PC 中不起作用? - Why Android Device Monitor Is Not Working In My PC? 我的应用程序正在我的Android模拟器上工作,但它不能在我的真实移动设备上工作 - My app is working on my android emulator however it is not working on my real mobile device Android呼叫过滤器可在我的设备上运行,但不能在客户端设备上运行 - Android Call Filter working on my device, but not client's device Web服务请求在android浏览器和代码中不起作用; 但它在PC浏览器中工作 - Web Service request is not working in android browser and code; but it is working in pc browser Java无法在我的电脑上运行 - Java is not working in my PC Android Studio-APK无法在我的设备上运行 - Android Studio - APK not working on my device Android设备到PC的套接字连接 - Android device to PC's socket connection 我的Android应用程序在模拟器上运行,但无法在我的Android设备上运行 - My Android application runs on emulator but not working on my android device 无法获得适用于Android的GET请求 - Cannot get GET request working for Android 如何让 BluetoothAdapter.startDiscovery() 在我的 Android 10 设备上工作? - How do I get the BluetoothAdapter.startDiscovery() working on my Android 10 device?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM