Android HttpUrlConnection连接始终失败

时间:2016-03-21 13:14:59

标签: android httpurlconnection

我开发了一个需要HttpUrlConnection的程序。问题是httpConn.connect()永远不会成功。我已检查网络连接是否可用且状态是否已连接。

    InputStream in = null;
    int resCode = -1;

    try {
        URL url = new URL(urlStr);
        URLConnection urlConn = url.openConnection();

        if (!(urlConn instanceof HttpURLConnection)) {
            throw new IOException("URL is not an Http URL");
        }
        HttpURLConnection httpConn = (HttpURLConnection) urlConn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        resCode = httpConn.getResponseCode();

        if (resCode == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }*/
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

在onCreate方法中添加以下代码只会阻止程序强行关闭。

if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

我在清单

中添加了这些权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

有我的:

public class YourClass extends AsyncTask<String, String, String> {

private AsyncResponse listener; //The listener interface
HttpURLConnection conn = null; //New object HttpURLConnection



public YourClass(AsyncResponse listener){
    this.listener=listener;
    //Params you need in this class
}

protected void onPreExecute() {
    //Job you need to do before execute
}


@Override
protected String doInBackground(String... params) {

    String response = "";
    String responseError = "";

    try{
        //Connect to URL
        Log.d("JSON", "Start of connexion");
        URL url = new URL(params[0]);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.connect();

        int responseCode=conn.getResponseCode();

        //HTTP_OK --> 200
        //HTTP_CONFLICT --> 409
        if (responseCode == HttpsURLConnection.HTTP_OK ) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
            return response;
        }
        else if(responseCode == HttpURLConnection.HTTP_CONFLICT){
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            while ((line=br.readLine()) != null) {
                responseError+=line;
            }
            return responseError;
        }
        else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null){
            conn.disconnect();
        }

    }

        return null;
}

     @Override
     protected void onPostExecute(String result) {
        try{
             super.onPostExecute(result);
             listener.onTaskCompleted(result);
         }
         catch(NullPointerException npe){
             Log.d("NullPointerException", npe.getMessage());
         }
    }
}

AsynResponse是一个接口,我将这个接口实现给调用我的AsyncTask的类,我重写方法OnTaskComplete。当AsyncTask完成时,这个方法就是调用。

更多信息:How to get the result of OnPostExecute()

我如何在我的Activity中实现AsynResponse接口的这个类:

new YourClass(this).execute("http://myUrl.com");

我希望这有帮助。