Подключение к БД с использованием интерфейса REST: Невозможно подключиться - PullRequest
2 голосов
/ 11 января 2012

Я пытаюсь подключиться к mongodb через REST-интерфейс mongolabs в разрабатываемом приложении для Android, но оно не подключается, а вместо этого выдает исключение (или, по крайней мере, я так думаю).Я не знаком с бэкэндами, поэтому, если я совершаю роковую ошибку новичка, пожалуйста, прости меня.Это logcat

01-10 16: 28: 50.377: W / System.err (630): javax.net.ssl.SSLException: имя хоста в сертификате не совпадает:! = ИЛИИЛИ> 01-10 16: 28: 50.377: W / System.err (630): at org.apache.http.conn.ssl.AbstractVerifier.verify (AbstractVerifier.java:185) 01-10> 16: 28: 50.388: W / System.err (630): в org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify (BrowserCompatHostnameVerifier.java:54)

Ниже приведена часть класса MongoLabHelper, для которого я написалполучить доступ к базе данных и получить такие элементы, как имена

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

, и вот часть класса, в котором он используется

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

Ответы [ 3 ]

3 голосов
/ 11 января 2012

На самом деле вам нужно явно настроить HttpClient для обработки SSL. Я полагаю, что этот поток stackoverflow содержит необходимую информацию:

Безопасный пост HTTP в Android

Для удобства я скопирую соответствующий бит кода из потока:

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);
}
0 голосов
/ 01 сентября 2013

У вас есть пример здесь из приложения http://lolapriego.com/blog/?p=16

или вы можете взглянуть на этот Gist, где вы можете увидеть, как сделать http-запрос в 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();
            }
        }
    }
}

}* +1007 *

0 голосов
/ 09 июля 2013

как помощник;
Я также реализовал библиотеку Android, чтобы абстрагировать коммуникацию MongoLab.
Основная цель - создать простую в использовании библиотеку, которая использует возможности Mongo в облаке, прямо из приложений Android!
Примечание: я также включил собственный репортер ACRA, который использует MongoLab.

вот первая версия (я буду продолжать расширяться) :
-> https://github.com/wareninja/mongolab-sdk

...