使用 REST 接口连接到数据库:无法连接

Posted

技术标签:

【中文标题】使用 REST 接口连接到数据库:无法连接【英文标题】:Connecting to a db using REST interface: Cannot connect 【发布时间】:2012-01-10 23:04:00 【问题描述】:

我正在尝试通过我正在开发的 android 应用程序中的 mongolabs REST 接口连接到 mongodb,但它没有连接,而是抛出异常(或者至少我认为是)。我对后端不熟悉,所以如果我犯了一个致命的菜鸟错误,请原谅我。这是日志猫

01-10 16:28:50.377: W/System.err(630): javax.net.ssl.SSLException: 证书中的主机名不匹配:!= OR OR >01-10 16:28:50.377 : W/System.err(630): 在 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);

【问题讨论】:

【参考方案1】:

您实际上需要显式设置 HttpClient 来处理 SSL。我相信这个 *** 线程有你需要的信息:

Secure HTTP Post in 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);

【讨论】:

【参考方案2】:

作为助手; 我还实现了 Android 库来抽象 MongoLab 通信。 主要目标是创建一个易于使用的库,该库可直接从 Android 应用程序中利用云中 Mongo 的强大功能! 注意:我还包含了使用 MongoLab 的自定义 ACRA 报告器。

这是第一个版本(我会继续扩展): ->https://github.com/wareninja/mongolab-sdk

【讨论】:

【参考方案3】:

这里有一个来自应用程序 http://lolapriego.com/blog/?p=16 的示例

或者您可以查看此 Gist,您可以在其中了解如何在 Android 中发出 http 请求

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

【讨论】:

以上是关于使用 REST 接口连接到数据库:无法连接的主要内容,如果未能解决你的问题,请参考以下文章

设备连接到 WiFi 接口时无法识别 WiFi Direct 对等体

无法在localhost上与Zend_Rest_Client连接错误

vcenter克隆无法连接到主机

连接网站显示数据库错误:无法连接到数据库:无法连接到MySQL?

无法使用 sqlplus 连接到数据库:ORA-12154:TNS:无法解析指定的连接标识符

无法使用php连接错误连接到mysql:无法连接到'localhost'(10061)上的MySQL服务器[重复]