2012-07-16 12 views
6

Estoy tratando de conectar a través de HttpPost y enviar un nombre de usuario y contraseña a un sitio web y luego recibir una cadena de ese sitio web. He intentado varios métodos que han funcionado para mí en el pasado, pero ahora cuando envío los identificadores de usuario y contraseña los tiempos de aplicación a cabo durante el tiempo de 4 minutos y luego escupe la siguiente excepción: el permisoHttpHostConnectException: Conexión rechazada 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 

internet está activado en mi archivo de manifiesto XML

mi implementación actual es la siguiente:

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

Y la clase HttpHelperAndroid se ve así:

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

Y aquí es mi XML, sólo por diversión:

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

He utilizado la clase HttpHelper en proyectos anteriores y ha funcionado para mí, además Traté de poner en práctica esto utilizando 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)); 

Y esto produjo el mismo resultado.

Podría esto de alguna manera ser una cosa certificado? o tal vez algo que ver con un archivo XML corrupto (intenté rehacer el proyecto y el archivo xml) Android HTTP Connection refused ¿O tal vez algún tipo de problema con el archivo de hosts de Android?

¡Estoy abierto a cualquier sugerencia!

He examinado esto desde muchos ángulos y estoy feliz de proporcionar cualquier otra información que pueda ser útil! ¡Realmente aprecio tu tiempo!

NOTA: La url es una URL ficticia, y no la real a la que me estoy conectando, por razones de seguridad. Puedo curvar el sitio web real desde la línea de comandos con los parámetros y funciona, y también puedo iniciar sesión normalmente desde el navegador web.

EDITAR He identificado el problema! Pero desafortunadamente no es la solución. Entonces, el problema es que estoy usando una URL del servidor de desarrollo que no tiene una entrada de dominio en el servidor DNS global. Entonces, para arreglar esto, de alguna manera necesito editar el archivo de hosts en mi dispositivo Android/en el emulador ... ¿alguien sabe cómo se puede hacer esto legítimamente?

+1

De acuerdo con la segunda línea en su Logcat: > 07-16 16: 32: 32.907: W/System.err (632): org.apache.http.conn.HttpHostConnectException: Conexión a http: // devdashboard .company se negó. ¿Estás seguro de que esto no es solo un problema de red en lugar de un problema con tu código? ¿Ha comprobado la configuración del servidor? –

+0

¿Estás seguro de que debería ser una publicación? –

+0

también limite lo que publica. Debe editar la información que sea específica para su entorno. –

Respuesta

9

¡He identificado el problema! Entonces, el problema es que estoy usando una URL del servidor de desarrollo que no tiene una entrada de dominio en el servidor DNS global.

Así que hay dos posibles soluciones a este problema:

1) Editar el archivo hosts en el dispositivo Android (requiere las raíces de su teléfono): How to change the hosts file on android

2) Conseguir el servidor registrado en el DNS mundial servidor. (también es difícil de hacer si no es responsable de la url)

De todos modos espero que esto ayude a alguien más también!

2

Hay algunas posibilidades

1) La URL es incorrecta "http://devdashboard.company/login" no está bien. Al menos comprobar en el navegador. ping el host también.

2) Esto debería ser una conexión HTTPS en su lugar.

3) se requiere alguna certificación.

4) Falta un número de puerto. o el dominio no se ha configurado correctamente. quizás el puerto 80, ¿el valor predeterminado es incorrecto?

5) la llamada no debe ser una publicación.

En general, usted es responsable del servidor o no lo es. Parece que es responsabilidad de algunos, y debería preguntarles cuál es la url y los parámetros correctos. Por lo tanto, probablemente no sea culpa de ninguno, pero debe preguntarles sobre la conexión para verificar.

Lo otro que puede hacer es tratar de ver cómo es la url en una aplicación que está conectando correctamente. Echa un vistazo que esto.

+0

¡Gracias por su respuesta! Entonces, la url es una urna ficticia que utilicé para proteger el servidor. Editaré mi pregunta para reflejar eso. Entonces, ¿qué debería ser sino una publicación? – VinC

+0

Así que soy capaz de curl desde la línea de comandos con los parámetros anteriores, así que creo que es una publicación, y esa es otra razón por la que me hace pensar que es un problema con mi código. Además, definitivamente debería ser https, pero lo he intentado con ambos durante mis esfuerzos por resolver el problema. ¿Sabes si la certificación podría estar causando esto/cómo podría verificar? – VinC

+0

¡Descubrí cuál es el problema! Ver la edición de mi pregunta – VinC

2

El problema está en wifi para dormir. Utilice

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

y el permiso:

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

siga estas solución puede estar entre estos uno a resolver su problema.

1> compruebe allí su permiso de archivo de manifiesto o no.

2> compruebe su url con el navegador por el cliente de reposo y pase la solicitud correspondiente.

3> abrir la URL móvil, como: - dirección http://your IP/Puerto que es sólo para la comprobación ¿tiene un permiso o no para abrir esta URL en el móvil.

1

Esta publicación es antigua, pero es el primer resultado al buscar este error en Google. Encontré la misma excepción, y todo fue completamente correcto en mi código. Comenté la línea que contenía el permiso de INTERNET en mi AndroidManifest.xml, ejecuté la aplicación, hice clic/presioné mi botón para enviar la solicitud HTTP y obtuve la excepción, cerré la aplicación, volví al manifiesto, la línea de permiso fue descomentada, ejecuté la aplicación de nuevo, ¡y la excepción fue resuelta!

Este tipo de errores en 2015 (y en herramientas "avanzadas" como las últimas herramientas de compilación para Android API 21 e Intellij IDEA 14) me vuelven loco. ¡Estás llegando a tu fecha límite, y este tipo de errores interrumpe por completo tu trabajo!

Cuestiones relacionadas