2012-07-16 92 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的最新编译工具等“高级”工具)令我发疯!你正在接近你的最后期限,这种错误彻底破坏了你的工作!