HTTPS在Android中

时间:2011-08-02 15:08:43

标签: android

我已经实现了HTTP Post将数据发布到后端。如何在Android中实现HTTPS(我已经为https配置了后端)?

我用Google搜索并找到了一些解决方案: Secure HTTP Post in Android

并尝试了它们但我在后端没有收到任何数据。

这是正确的实施方式吗?还有其他方法吗?

以下是我的代码段:

              File file = new File(filepath);
         HttpClient client = new DefaultHttpClient();

             //String url = "http://test.....;
             String url = "https://test......";

         HttpPost post = new HttpPost(url);
             FileEntity bin = new FileEntity(file, url);

             post.setEntity(bin);

             HttpResponse response =  client.execute(post); 

             HttpEntity resEntity = response.getEntity();

基本上我使用fileentity来执行HTTPPost。现在我想通过https执行此操作。在后端实施https后,我刚刚在网址中将http修改为https并再次进行测试。它没有用。

我知道如何解决这个问题?

先谢谢, Perumal

1 个答案:

答案 0 :(得分:0)

确保您的http客户端支持SSL套接字:

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    HttpParams params = new BasicHttpParams();
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); 
    HttpClient httpsClient = new DefaultHttpClient(manager, params);

并使用此客户端执行您的POST请求:

    HttpPost post = new HttpPost("https://www.mysecuresite.com");
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setEntity(new StringEntity("This is the POST body", HTTP.UTF_8));

    HttpResponse response = httpsClient.execute(post);