2016-03-21 113 views
0

我开发的程序需要HttpUrlConnection。问题是httpConn.connect()从来没有成功。我已检查网络连接是否可用并且状态是否已连接。Android HttpUrlConnection连接始终失败

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

可能是url不正确! –

+2

你是否在UI线程上执行它?如果是这样,那么做另一个线程,如异步任务 –

回答

0

有雷:

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()


我如何在我的活动谁实现AsynResponse接口使用这个类:

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

我希望这帮助。