HttpHostConnectException:连接被拒绝的Andr​​oid [英] HttpHostConnectException: Connection refused Android

查看:714
本文介绍了HttpHostConnectException:连接被拒绝的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过HttpPost连接并发送用户名和密码到网站,然后接收来自该网站的字符串。我曾尝试在过去已经为我工作,但现在各种方法,当我发送的用户名和密码识别应用程序超时了长达4分钟,然后吐出了以下异常:

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:

 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

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

Internet permission IS enabled in my XML manifest file

我目前的执行情况是这样的:

My current implementation goes like this:

  String LOGIN = "email@gmail.com";
        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类看起来像这样:

And the HttpHelperAndroid class looks like so:

     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只是踢:

And here is my XML just for kicks:

<?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中:

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

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

和此,得到相同的结果。

And this yielded the same result.

难道这在某种程度上是证书的事情吗?或者是与腐败的XML文件(我试过改造项目和XML文件) Android的HTTP连接被拒绝 或者,也许某种Android系统主机文件的问题?

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 refused Or maybe some sort of Android hosts file issue?

我愿意接受任何建议!

我已经研究过这从很多角度,我很乐意提供,这将是有帮助的任何其他信息!我真的AP preciate你的时间!

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!

注意:的URL是一个虚拟的网址,而不是实际的一个我很连接,出于安全原因。我能够卷曲实际的网站从与参数的命令行和它的作品,我也可以从Web浏览器正常登录。

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不具有全球DNS服务器上的域条目。因此,要解决这个问题我有点需要编辑主机我的Andr​​oid设备上的文件/在模拟器......没有人知道这是如何合法地做什么?

EDIT I 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服务器上的域条目。

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.

因此​​,有两种可能的解决这个问题:

So there are two possible solutions to this issue:

1)编辑主机的Andr​​oid设备上的文件(需要生根您的手机):如何更改主机上Android文件

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

2)获得注册的全球DNS服务器上的服务器。 (也很难,如果你不负责的URL来)

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

反正我希望这可以帮助别人呢!

Anyways I hope this helps someone else too!

这篇关于HttpHostConnectException:连接被拒绝的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆