android - 网络调用在 android 中抛出 IO 异常和连接被拒绝在 android 设备中不工作

标签 android http network-protocols

我正在尝试从 Instagram 中获取值Web 服务器,在我的代码中,在模拟器中工作正常但在 Android 设备中不工作。它说 IOException并且连接被拒绝错误。

我给了<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>Manifest文件, URL我用过的是https://api.instagram.com/v1/users/[here用户 id ]/?access_token=此处访问 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);
        }
    }
}

只能在设备上工作,它在模拟器上工作

最佳答案

首先检查设备是否有 Activity 的互联网连接,然后如果为真则建立 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
}

希望对您有所帮助。

关于android - 网络调用在 android 中抛出 IO 异常和连接被拒绝在 android 设备中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23542594/

相关文章:

java - Jetty 中 HTTP-Response 状态码中的 Unicodes

android - 上传视频时出现问题 : Stream was reset: NO_ERROR

android - 如何在我的 Android 应用程序中展示 VAST 广告?

android - 芯片组多排芯片

http - 在 Servlet 中发送和接收二进制数据

html - 制作 'Confirm' 页面的最佳方法?

http - 为什么一些互联网提供商关闭某些端口?

networking - 自定义协议(protocol)的应用程序数据是否需要校验和?

java - 使用java连接到本地网络设备

android - Xamarin Studio 中未呈现自定义可绘制对象