Pregunta

Estoy tratando de conectarme a un MongoDB a través de la interfaz REST de Mongolabs en la aplicación de Android que estoy desarrollando, pero no se está conectando, y en su lugar está lanzando una excepción (o al menos creo que lo es). No estoy familiarizado con los backends, así que si estoy cometiendo un error fatal de novato, por favor perdóname. Este es el logcat

01-10 16: 28: 50.377: w/system.err (630): javax.net.ssl.sslexception: el nombre de host en certificado no coincidió :! = o> 01-10 16: 28: 50.377: w/ System.err (630): en org.apache.http.conn.ssl.abstractVerifier.verify (abstractverifier.java:185) 01-10> 16: 28: 50.388: w/system.err (630): en org. apache.http.conn.ssl.browserCompathostNameverifier.verify (browserCompathostNameverifier.java:54)

A continuación se muestra la parte de la clase Mongolabhelper que escribí para acceder a la base de datos y obtener elementos como nombres

HttpClient client;
JSONObject db;

MongoLabHelper() throws ClientProtocolException, IOException, JSONException{
    client = new DefaultHttpClient();
    HttpGet request = new HttpGet("https://api.mongolab.com/api/1/databases/breadcrumbs/collections/crumbs?apiKey=xxxxxxxxxxxxx");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    InputStream in = entity.getContent();
    String json = in.toString();
    db = new JSONObject(json); 
}

public String getName(String name) throws JSONException {
    JSONObject doc = db.getJSONObject(name);
    return doc.getString("name");               
}

y aquí está en parte la clase en la que se usa

   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String name = "Crumb Not Available";

    MongoLabHelper help;
    try {
        help = new MongoLabHelper();
        name = help.getName("Chipotle");
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




    setContentView(R.layout.breadcrumb);
    TextView crumbName = (TextView) findViewById(R.id.crumb_name);
    crumbName.setText(name);
¿Fue útil?

Solución

En realidad, debe configurar explícitamente el httpclient para manejar SSL. Creo que este hilo de StackOverflow tiene la información que necesita:

Secure HTTP Post en Android

Copiaré el bit de código relevante del hilo por conveniencia:

private HttpClient createHttpClient()
{
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    return new DefaultHttpClient(conMgr, params);
}

Otros consejos

Como un ayudante;
También he implementado la biblioteca de Android para abstracto Mongolab Communication.
¡El objetivo principal es facilitar una biblioteca que aproveche el poder de Mongo en la nube, directamente de las aplicaciones de Android!
Nota: También he incluido ACRA Reporter personalizado que usa Mongolab.

Aquí está la primera versión (Seguiré extendiendo):
-> https://github.com/wareninja/mongolab-sdk

Tienes un ejemplo aquí de una aplicación http://lolapriego.com/blog/?p=16

O puede echar un vistazo a esta esencia donde puede ver cómo hacer una solicitud HTTP en Android

public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

/** Single instance of our HttpClient */
private static HttpClient mHttpClient;

/**
 * Get our single instance of our HttpClient object.
 *
 * @return an HttpClient object with connection parameters set
 */
private static HttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
    return mHttpClient;
}

/**
 * Performs an HTTP Post request to the specified url with the
 * specified parameters.
 *
 * @param url The web address to post the request to
 * @param postParameters The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpPost(String url, JSONObject json) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF-8")));
        request.setHeader( "Content-Type", "application/json");

        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/**
 * Performs an HTTP GET request to the specified url.
 *
 * @param url The web address to post the request to
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpGet(String url) throws Exception {
    BufferedReader in = null;
    String data = null;

    try {
        HttpClient client = getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        response.getStatusLine().getStatusCode();

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while ((l = in.readLine()) !=null){
            sb.append(l + nl);
        }
        in.close();
        data = sb.toString();
        return data;        
    } finally{
        if (in != null){
            try{
                in.close();
                return data;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

/**
 * Performs an HTTP DELETE request to the specified url.
 *
 * @param url The web address to post the request to
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpDelete(String url) throws Exception {
    BufferedReader in = null;
    String data = null;

    try {
        HttpClient client = getHttpClient();
        HttpDelete request = new HttpDelete();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        response.getStatusLine().getStatusCode();

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while ((l = in.readLine()) !=null){
            sb.append(l + nl);
        }
        in.close();
        data = sb.toString();
        return data;        
    } finally{
        if (in != null){
            try{
                in.close();
                return data;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

/**
 * Performs an HTTP Put request to the specified url with the
 * specified parameters.
 *
 * @param url The web address to post the request to
 * @param putParameters The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */
public static String executeHttpPut(String url, JSONObject json) throws Exception {
    BufferedReader in = null;
    try {
        HttpClient client = getHttpClient();
        HttpPut request = new HttpPut(url);

        request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF-8")));
        request.setHeader( "Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();

        String result = sb.toString();
        return result;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top