HttpHostConnectException:连接被拒绝 Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11514038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:52:54  来源:igfitidea点击:

HttpHostConnectException: Connection refused Android

androidjsonhttpshttp-post

提问by VinC

I am trying to connect via HttpPost and send a username and password to a website and then receive a string from that website. I have tried various methods that have worked for me in the past but now when I send the username and password identifiers the app times out for as long as 4 minutes and then spits out the following exception:

我正在尝试通过 HttpPost 连接并将用户名和密码发送到网站,然后从该网站接收字符串。我尝试了过去对我有用的各种方法,但是现在当我发送用户名和密码标识符时,应用程序超时长达 4 分钟,然后吐出以下异常:

 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.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

Internet permission IS enabled in my XML manifest file

我的 XML 清单文件中启用了 Internet 权限

My current implementation goes like this:

我目前的实现是这样的:

  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");
    }

And the HttpHelperAndroid class looks like so:

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

And here is my XML just for kicks:

这是我的 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>

I have used the HttpHelper class in past projects and it has worked for me, in addition I tried to implement this using nameValuePairs:

我在过去的项目中使用过 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));

And this yielded the same result.

这产生了相同的结果。

Could this somehow be a certificate thing? or perhaps something to do with a corrupt XML file( I tried remaking the project and the xml file) Android HTTP Connection refusedOr maybe some sort of Android hosts file issue?

这会以某种方式成为证书吗?或者可能与损坏的 XML 文件有关(我尝试重新制作项目和 xml 文件)Android HTTP 连接被拒绝或者可能是某种 Android 主机文件问题?

I'm open to any suggestions!

我愿意接受任何建议!

I have examined this from a lot of angles and I'm happy to provide any other information that would be helpful! I really appreciate your time!

我从很多角度对此进行了研究,我很高兴提供任何其他有用的信息!我真的很感激你的时间!

NOTE:The url is a dummy url, and not the actual one I am connecting to, for security reasons. I am able to curl the actual website from the command line with the parameters and it works and I am also able to login normally from the web browser.

注意:出于安全原因,该 url 是一个虚拟 url,而不是我正在连接的实际 url。我可以使用参数从命令行 curl 实际网站并且它可以工作,我也可以从 Web 浏览器正常登录。

EDITI have identified the problem! But not the solution unfortunately. So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server. So to fix this I somehow need to edit the hosts file on my Android device/in the emulator...does anyone know how this can be done legitimately?

编辑我已经确定了问题!但不幸的是,这不是解决方案。所以问题是我使用的开发服务器 url 在全局 DNS 服务器上没有域条目。所以为了解决这个问题,我需要在我的 Android 设备上/在模拟器中编辑主机文件......有谁知道如何合法地做到这一点?

回答by VinC

I have identified the problem! So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server.

我已经确定了问题所在!所以问题是我使用的开发服务器 url 在全局 DNS 服务器上没有域条目。

So there are two possible solutions to this issue:

所以这个问题有两种可能的解决方案:

1) Editing the hosts file on the Android device (requires rooting your phone): How to change the hosts file on android

1)在Android设备上编辑hosts文件(需要root手机):如何在Android上更改hosts文件

2) Getting the server registered on the global DNS server. (also hard to do if you're not responsible for the url)

2) 获取在全球DNS服务器上注册的服务器。(如果您不对网址负责,也很难做到)

Anyways I hope this helps someone else too!

无论如何,我希望这对其他人也有帮助!

回答by Rohit Bandil

Please follow these solution may be among these one solve your issue.

请按照这些解决方案可能是其中之一解决您的问题。

1> check your manifest file internet permission there or not.

1> 检查您的清单文件 Internet 权限是否存在。

2> check your url with browser by rest client and pass the appropriate request.

2>通过rest客户端使用浏览器检查您的网址并传递适当的请求。

3> open the url in mobile like:- http://yourip address/portthat's it just for checking do you have a permission or not to open this url in mobile.

3> 在手机中打开网址,例如:- http://您的IP 地址/端口,这只是为了检查您是否有权在手机中打开此网址。

回答by Code Droid

There are a few possibilities

有几种可能

1) the url is incorrect "http://devdashboard.company/login" is not right. At least check in browser. ping the host as well.

1) url 不正确“http://devdashboard.company/login”不正确。至少在浏览器中检查。ping主机也是如此。

2) This should be an https connection instead.

2) 这应该是一个 https 连接。

3) there is some certification required.

3)需要一些认证。

4) You are missing a port number. or domain has not been setup correctly. perhaps port 80 the default is incorrect?

4) 您缺少端口号。或域未正确设置。也许端口 80 默认不正确?

5) the call should not be a post.

5)电话不应该是帖子。

In general you are either responsible for the server or you are not. It appears that it is some elses responsibility, and you should ask them what the correct url and parameters are. So its probably no ones fault, but you need to ask them about the connection to verify.

通常,您要么对服务器负责,要么不负责。看起来是别人的责任,你应该问他们正确的url和参数是什么。所以它可能没有人的错,但你需要向他们询问要验证的连接。

The other thing you can do is to try and see what the url looks like in an application that is succesfully connectiing. take a look that this.

您可以做的另一件事是尝试查看成功连接的应用程序中 url 的样子。看看这个。

回答by user1575120

The problem is in wifi sleeping. Please use

问题在于wifi睡眠。请用

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

and permission:

和许可:

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

回答by Javad Sadeqzadeh

This post is old, but it is the first result when googling this error. I encountered the same exception, and everything was completely correct in my code. I commented out the line containing the INTERNET permission in my AndroidManifest.xml, ran the app, clicked/tapped my button to send the HTTP request and get the exception, closed the app, went back to the manifest, uncommented the permission line, ran the app again, and the exception was resolved!

这篇文章很旧,但它是谷歌搜索此错误时的第一个结果。我遇到了同样的异常,我的代码中的一切都是完全正确的。我在 AndroidManifest.xml 中注释掉了包含 INTERNET 权限的行,运行应用程序,单击/点击我的按钮发送 HTTP 请求并获取异常,关闭应用程序,返回清单,取消注释权限行,运行再次运行应用程序,异常已解决!

This kind of bugs in 2015 (and in "advanced" tools like the latest compile tools for Android API 21, and Intellij IDEA 14) drives me mad! You are approaching your deadline, and this sort of bugs completely disrupts your work!

2015 年的这种错误(以及“高级”工具中的错误,例如适用于 Android API 21 和 Intellij IDEA 14 的最新编译工具)让我发疯!你快到最后期限了,这种错误完全扰乱了你的工作!