网络调用抛出 IO 异常并且在 android 中拒绝连接在 android 设备中不起作用

Posted

技术标签:

【中文标题】网络调用抛出 IO 异常并且在 android 中拒绝连接在 android 设备中不起作用【英文标题】:Network call throws IO exception and connection refused in android not working in android device 【发布时间】:2014-06-25 21:27:17 【问题描述】:

我正在尝试从 Instagram 网络服务器获取值,在我的代码中,在模拟器中运行良好,但在 android 设备中运行不正常。它说 IOException 和连接被拒绝错误。

我在Manifest文件中给出了<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>, 我使用的URL 是https://api.instagram.com/v1/users/[here user id ]/?access_token=here access token

对于我正在使用的网络呼叫:

URL url = new URL(urls);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
result = new JSONObject(response);`

streamToString 是方法:

private String streamToString(InputStream is) throws IOException 
    String str = "";

    if (is != null) 
        StringBuilder sb = new StringBuilder();
        String line;

        try 
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) 
                sb.append(line);
            

            reader.close();
         finally 
            is.close();
        
        str = sb.toString();
    
    return str;

我的 AsyncTask 类

public class JSONParser extends AsyncTask<Void, Void, JSONObject> 

private Context context;
private Error error;
private RequestListener callback;
private ProgressDialog progressDialog;
private String url;

public JSONParser(Context context, String url, RequestListener callback) 
    this.context = context;
    this.callback = callback;
    this.error = Error.UNKNOWN;
    this.url = url;

public JSONParser showProgressDialog(int messageId) 
    return showProgressDialog(null, context.getString(messageId));

public JSONParser showProgressDialog(String message) 
    return showProgressDialog(null, message);

public JSONParser showProgressDialog(int titleId, int messageId) 
    return showProgressDialog(context.getString(titleId), context.getString(messageId));

public JSONParser showProgressDialog(String title, String message) 
    progressDialog = new ProgressDialog(context);
    if (title != null) 
        progressDialog.setTitle(title);
    
    progressDialog.setMessage(message);
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    return this;


@Override
protected void onPreExecute() 
    if (progressDialog != null) 
        progressDialog.show();
    


@Override
protected JSONObject doInBackground(Void... params) 

    JSONObject result = null;
    if (isNetworkReachable()) 
        try 

            String urls = url;
            URL url = new URL(urls);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.connect();
            String response = streamToString(urlConnection.getInputStream());
            result = new JSONObject(response);
         catch (IOException e) 
            ALog.e("IOException : %s", e.getMessage());
            error = Error.IO_ERROR;
         catch (ParseException e) 
            ALog.e("ParseException : %s", e.getMessage());
            error = Error.PARSE_ERROR;
         catch (JSONException e) 

            ALog.e("JSONException : %s", e.getMessage());
            error = Error.PARSE_ERROR;
         catch (Exception e) 
            ALog.e("UnknownException : %s", e.getMessage());
            error = Error.UNKNOWN;
        
     else 
        error = Error.NETWORK_UNAVAILABLE;
    
    return result;


private String streamToString(InputStream is) throws IOException 
    String str = "";

    if (is != null) 
        StringBuilder sb = new StringBuilder();
        String line;

        try 
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is));
            while ((line = reader.readLine()) != null) 
                sb.append(line);
            

            reader.close();
         finally 
            is.close();
        
        str = sb.toString();
    
    return str;


@Override
protected void onPostExecute(JSONObject jsonObject) 
    if (progressDialog != null) 
        progressDialog.dismiss();
    
    if (!isCancelled()) 
        if (jsonObject != null) 
            callback.onRequestSuccess(jsonObject);
         else 
            callback.onRequestFailure(error);
        
    

只在设备上不工作,在模拟器上工作

【问题讨论】:

JSONParser.doInBackground@77: IOException : 和我给出的链接一样在这里 @John 请发布完整的 logcat,而不仅仅是它的一部分 我认为你没有使用 asynctask 来获取数据。这就是它给你异常的原因。也发布你的 logcat @nikis 我只在上面一行,我再次粘贴在这里 JSONParser.doInBackground@77: IOException : api.instagram.com/v1/users/[here user id ]/?access_token=[这里访问令牌] @John 尝试致电e.printStackTrace() 查看完整图片 【参考方案1】:

首先检查设备是否有活动的互联网连接,如果是,则建立 http 连接。 像这样:

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();
if (isConnected) 
  URL url = new URL(urls);
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoInput(true);
  urlConnection.setDoOutput(true);
  urlConnection.connect();

// more stuff here

希望对你有帮助。

【讨论】:

以上是关于网络调用抛出 IO 异常并且在 android 中拒绝连接在 android 设备中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

抛出异常:尝试调用 WCF 服务时 mscorlib.dll 中的“System.IO.FileNotFoundException”

Android 5.0+ MediaPlayer 在尝试播放 OPUS 文件时抛出 PreparedFailed 异常

自己定义Application的未捕获异常处理

调用函数时模拟器抛出异常(android studio)

java中如何获取throws抛出的异常,并且把异常打印到指定的jsp页面

Android - 接口callBack抛出空指针异常