2012-07-16 233 views
6

我試圖通過HttpPost連接併發送用戶名和密碼到網站,然後從該網站接收到一個字符串。我曾嘗試在過去爲我工作,但現在各種方法,當我發送的用戶名和密碼識別出應用時間長達4分鐘,然後吐出來的是以下情況例外:HttpHostConnectException:連接被拒絕Android

07-16 16:32:32.897: W/System.err(632): Unable to connect to the server 
    07-16 16:32:32.907: W/System.err(632): org.apache.http.conn.HttpHostConnectException: Connection to http://devdashboard.company refused 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183) 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 
    07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 
    07-16 16:32:32.927: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 
    07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.HttpHelperAndroid.sendToHttp(HttpHelperAndroid.java:66) 
    07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.DashboardAppActivity.goToDashboard(DashboardAppActivity.java:62) 
    07-16 16:32:32.927: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method) 
    07-16 16:32:32.937: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511) 
    07-16 16:32:32.937: W/System.err(632): at android.view.View$1.onClick(View.java:3039) 
    07-16 16:32:32.947: W/System.err(632): at android.view.View.performClick(View.java:3511) 
    07-16 16:32:32.947: W/System.err(632): at android.view.View$PerformClick.run(View.java:14105) 
    07-16 16:32:32.947: W/System.err(632): at android.os.Handler.handleCallback(Handler.java:605) 
    07-16 16:32:32.957: W/System.err(632): at android.os.Handler.dispatchMessage(Handler.java:92) 
    07-16 16:32:32.957: W/System.err(632): at android.os.Looper.loop(Looper.java:137) 
    07-16 16:32:32.967: W/System.err(632): at android.app.ActivityThread.main(ActivityThread.java:4424) 
    07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method) 
    07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511) 
    07-16 16:32:32.977: W/System.err(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
    07-16 16:32:32.987: W/System.err(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
    07-16 16:32:32.987: W/System.err(632): at dalvik.system.NativeStart.main(Native Method) 
    07-16 16:32:32.987: W/System.err(632): Caused by: java.net.ConnectException: failed to connect to /50.19.240.232 (port 80): connect failed: ETIMEDOUT (Connection timed out) 
    07-16 16:32:32.997: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:114) 
    07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 
    07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 
    07-16 16:32:33.007: W/System.err(632): at java.net.Socket.connect(Socket.java:842) 
    07-16 16:32:33.007: W/System.err(632): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 
    07-16 16:32:33.017: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 
    07-16 16:32:33.017: W/System.err(632): ... 22 more 
    07-16 16:32:33.027: W/System.err(632): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out) 
    07-16 16:32:33.047: W/System.err(632): at libcore.io.Posix.connect(Native Method) 
    07-16 16:32:33.047: W/System.err(632): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85) 
    07-16 16:32:33.047: W/System.err(632): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 
    07-16 16:32:33.057: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:112) 
    07-1 
    6 16:32:33.057: W/System.err(632): ... 27 more 

上網權限在我的XML清單文件啓用

我當前的實現是這樣的:

String LOGIN = "[email protected]"; 
     String PASSWORD ="password1"; 

     //JSONObject to send the username and pw 
     JSONObject json = new JSONObject(); 
     //put the path in the JSONArray object 

     JSONArray vect = new JSONArray(); 
     vect.put("company Android Library"); 
     vect.put("Rocket Ship"); 

     int duration = 50; 
     try { 
      json.put("email", LOGIN); 
      json.put("password", PASSWORD); 
      json.put("json", "true"); 


     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     Log.d(TAG, "ABOUT TO SEND:" + json.toString()); 

     JSONObject inJson = HttpHelperAndroid.sendToHttp(json, "http://devdashboard.company/login"); 

     if(inJson != null) 
     { 
      Log.d(TAG, "RECIEVED the JSON:" + inJson.toString()); 
     } 
     else 
      Log.d(TAG, "THE RESPONSE WAS NULL"); 
    } 

而且HttpHelperAndroid類看起來像這樣:

 public class HttpHelperAndroid 
    { 
     private static final String TAG = "HttpHelperAndroid";//TAG for the LogCat(debugging) 


    private static boolean responseSuccessful = true; 

    /** 
    * sends the JSONObject parameter to the desired URL parameter and gets the response 
    * 
    * @param url the URL to which the JSONObject should be sent 
    * @param jsonObjOut the JSONObject that is to be sent 
    * @return the response from the server as a JSONObject 
    */ 
    public static JSONObject sendToHttp(JSONObject jsonObjOut, String url) { 
     responseSuccessful = true; 
     try 
     { 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpRequest = new HttpPost(url); 

      //convert the JSONObject to a string 
      StringEntity se; 

      //set our StringEntity to the JSONObject as a string 
      se = new StringEntity(jsonObjOut.toString()); 

      // Set HTTP params 
      httpRequest.setEntity(se); 
      httpRequest.setHeader("Accept", "application/json"); 
      httpRequest.setHeader("Content-type", "application/json"); 
      httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression 

      //get the current time 
      long oldTime = System.currentTimeMillis(); 

      HttpResponse response = null; 
      try 
      { 
       //execute the http request and get the response 
       response = (HttpResponse) httpClient.execute(httpRequest); 
      } 
      catch(HttpHostConnectException e) 
      { 
       System.err.println("Unable to connect to the server"); 
       e.printStackTrace(); 
       responseSuccessful = false; 
      } 

      //only continue executing if we got a response from the server 
      if(responseSuccessful) 
      { 
       //print how long the response took to the LogCat if it's on 

        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-oldTime) + "ms]"); 


       // Get hold of the response entity (-> the data): 
       HttpEntity entity = response.getEntity(); 

       if (entity != null) { 
        // Read the content stream 
        InputStream in = entity.getContent(); 
        Header contentEncoding = response.getFirstHeader("Content-Encoding"); 
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
         in = new GZIPInputStream(in); 
        } 

        // convert content stream to a String 
        String resultString= streamToString(in); 

        //close the stream 
        in.close(); 

        // convert the String into a JSONObject 
        JSONObject jsonObjRecv = new JSONObject(resultString); 

        //take a peak at the JSONObject we got back if the LogCat is on 

         Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>"); 

        //return the JSONObject we got back from the server 
        return jsonObjRecv; 
       } 
      } 
     } 
     //catch any exception that was thrown 
     catch (Exception e) 
     { 
      //Print the exception 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    private static String streamToString(InputStream is) 
    { 
     //create a new BufferedReader for the input stream 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 

     //create a new StringBuilder to append the lines 
     StringBuilder sb = new StringBuilder(); 

     //initialize an empty string 
     String line = null; 

     try 
     { 
      //iterate as long as there is still lines to be read 
      while ((line = reader.readLine()) != null) 
      { 
       //append the line and a newline character to our StringBuilder 
       sb.append(line + "\n"); 
      } 
     } 
     //catch an IOException and print it 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     //close the stream when we're done 
     finally 
     { 
      try 
      { 
       is.close(); 
      } 
      //catch and print an exception if it's thrown 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 
     } 
     //return the stream converted to a string 
     return sb.toString(); 
    } 
} 

這裏是我的XML只是踢:

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="company.android.dashboard.app" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-permission android:name="android.permission.INTERNET" /> 

    <uses-sdk android:minSdkVersion="7" /> 

    <application 
     android:icon="@drawable/company_android_ico" 
     android:label="@string/app_name" > 
     <activity 
      android:name=".DashboardAppActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

我已經使用了HttpHelper類在過去的項目,它很適合我,除了我試圖實現這個使用namevaluepairs中:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("email", "[email protected]")); 
     nameValuePairs.add(new BasicNameValuePair("password", "password1")); 
     nameValuePairs.add(new BasicNameValuePair("json", "true")); 
     try { 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

這產生了相同的結果。

難道這不知是一個證書的事情嗎?或者可能與某個損壞的XML文件有關(我嘗試重新制作該項目和xml文件)Android HTTP Connection refused 或者某種Android主機文件問題?

我願意接受任何建議!

我從很多角度對此進行了研究,我很樂意提供任何其他有用的信息!我非常感謝你的時間!

注意:該網址是一個虛擬網址,而不是我連接到的實際網址,出於安全原因。我可以從命令行使用參數控制實際的網站,它可以正常工作,我也可以通過Web瀏覽器正常登錄。

編輯我發現了問題!但不幸的是解決方案。所以問題是我正在使用在全局DNS服務器上沒有域項的開發服務器url。所以要解決這個問題,我需要編輯我的Android設備/模擬器上的主機文件...有誰知道這可以做到合理嗎?

+1

根據你的logcat的第二行: > 07-16 16:32:32.907:W/System.err的(632):org.apache.http.conn.HttpHostConnectException:連接到http:// devdashboard 。公司拒絕。 你確定這不僅僅是一個網絡問題,而不是你的代碼問題? 您是否檢查過服務器配置? – 2012-07-16 23:34:05

+0

你也確定它應該是一個職位? – 2012-07-16 23:38:45

+0

也請限制你發佈的內容。您應該編輯特定於您的環境的信息。 – 2012-07-16 23:47:15

回答

9

我發現了這個問題!所以問題是我正在使用在全局DNS服務器上沒有域項的開發服務器url。

所以有這個問題有兩個可能的解決方案:

1)編輯hosts文件在Android設備上(需要生根您的電話):How to change the hosts file on android

2)獲取在全球DNS註冊的服務器服務器。 (也很難做到如果你不負責的網址)

反正我希望這也能幫助別人!

2

有幾個可能性

1)的網址是不正確「http://devdashboard.company/login」是不正確的。至少檢查瀏覽器。 也可以ping主機。

2)這應該是一個https連接。

3)有一些認證要求。

4)您缺少端口號。或域沒有正確設置。 也許端口80的默認值是不正確的?

5)該電話不應該是一個職位。

一般來說,您要麼負責服務器,要麼不負責。看來,這是一些elses的責任,你應該問他們什麼是正確的網址和參數。所以它可能沒有任何錯誤,但你需要詢問他們關於連接的驗證。

您可以做的另一件事是嘗試在成功連接的應用程序中查看url的樣子。看看這個。

+0

感謝您的回覆!所以url是我用來保護服務器的虛擬url,我將編輯我的問題以反映這一點。那麼,如果不是一個職位,該怎麼辦? – VinC 2012-07-17 15:54:12

+0

所以我能夠從上面的參數在命令行中捲曲,所以我認爲這是一個帖子,這是它使我認爲這是我的代碼的一些問題的另一個原因。此外,它肯定應該是https,但我在嘗試解決問題時都嘗試過。你知道這個認證是否會導致這個/我怎麼檢查? – VinC 2012-07-17 16:15:40

+0

我發現問題是什麼!請參閱我的問題上的編輯 – VinC 2012-07-17 17:53:24

2

問題出在wifi睡眠。 請使用

WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock"); 
wifiLock.acquire(); 

和權限:

uses-permission android:name="android.permission.WAKE_LOCK"; 
2

請遵循這些解決方案可能是其中之一中解決您的問題。

1>檢查你的清單文件的互聯網許可有沒有。

2>通過休息客戶端瀏覽器檢查您的URL並傳遞適當的請求。

3>打開手機一樣的網址: - http://your IP地址/端口這只是爲了檢查你是否有許可或不移動,打開這個網址。

1

這篇文章已經過時了,但它是使用googling這個錯誤時的第一個結果。我遇到了同樣的異常,並且在我的代碼中一切都完全正確。我在AndroidManifest.xml文件中註釋了包含INTERNET許可權的行,運行了應用程序,單擊/點擊了我的按鈕以發送HTTP請求並獲取異常,關閉了應用程序,返回清單,取消註釋權限行,運行該應用程序再次,並且異常已解決!

2015年的這種錯誤(以及像「Android API 21」和Intellij IDEA 14的最新編譯工具等「高級」工具)令我發瘋!你正在接近你的最後期限,這種錯誤徹底破壞了你的工作!