如何做到从Android的一个HTTPS POST? [英] How to do an HTTPS POST from Android?

查看:171
本文介绍了如何做到从Android的一个HTTPS POST?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个HTTPS POST方法,从我的Andr​​oid应用程序发送一些数据到我的网站。

我用的HttpURLConnection 第一,它的正常工作与我的HTTP URL。我制作的网站是HTTPS和我想用 HttpsURLConnection 发送同一职位。有人可以帮助我使用类是否正确?

我发现了一些源在此链接

 密钥库的keyStore = ...;
的TrustManagerFactory TMF = TrustManagerFactory.getInstance(X509);
tmf.init(的keyStore);

的SSL连接上下文= SSLContext.getInstance(TLS);
context.init(空,tmf.getTrustManagers(),NULL);

网址URL =新的URL(https://www.example.com/);
HttpsURLConnection的URLConnection =(HttpsURLConnection)
url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
在的InputStream = urlConnection.getInputStream();
 

应该是什么密钥库密钥库的价值= ...;

我试着用同样的的HttpURLConnection 发送数据,但我看到一些POST数据遗漏或错误。

我试着从方法<一href="http://stackoverflow.com/questions/11218022/android-https-post-to-bitbucket-issue-tracker-returns-filenotfoundexception?rq=1">this问题。我在下面粘贴

我的code

 字符串urlParameters =日期时间=+ URLEn coder.en code(日期时间,UTF-8)+
    &放大器; mobileNum =+ URLEn coder.en code(mobileNum,UTF-8);

网址URL =新的URL(myurl);
HttpsURLConnection康涅狄格州;
康恩=(HttpsURLConnection)url.openConnection();

//创建SSL连接
的SSLContext SC;
SC = SSLContext.getInstance(TLS);
sc.init(NULL,NULL,新java.security.SecureRandom中的());
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setConnectTimeout(HTTP_CONNECT_TIME_OUT);
conn.setReadTimeout(HTTP_READ_TIME_OUT);

//输出设置为true,表示你是输出(上传)POST数据
conn.setDoOutput(真正的);
//一旦你设置输出为真,你并不需要设置请求方法来发布,但我这样做也无妨
conn.setRequestMethod(POST);
conn.setFixedLengthStreamingMode(urlParameters.getBytes()的长度。);
conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);

PrintWriter的输出=的新PrintWriter(conn.getOutputStream());
的out.print(urlParameters);
out.close();

InputStream的是= conn.getInputStream();
的BufferedReader在=新的BufferedReader(新InputStreamReader的(是));
字符串inputLine;
而((inputLine = in.readLine())!= NULL){
  响应+ = inputLine;
}
 

我得到的错误是如下:

  05-12 19:36:10.758:W / System.err的(1123):java.io.FileNotFoundException:https://www.myurl.com/fms/test
05-12 19:36:10.758:W / System.err的(1123):在libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
05-12 19:36:10.758:W / System.err的(1123):在libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
05-12 19:36:10.758:W / System.err的(1123):在的.htt prequest(SMSToDBService.java:490)
05-12 19:36:10.758:W / System.err的(1123):在com..access $ 0(SMSToDBService.java:424)
05-12 19:36:10.758:W / System.err的(1123):在COM $ ChildThread $ 1.handleMessage(SMSToDBService.java:182)
05-12 19:36:10.758:W / System.err的(1123):在android.os.Handler.dispatchMessage(Handler.java:99)
05-12 19:36:10.758:W / System.err的(1123):在android.os.Looper.loop(Looper.java:156)
05-12 19:36:10.758:W / System.err的(1123):在COM $ ChildThread.run(SMSToDBService.java:303)
 

解决方案

您可以使用在Android设备中定义的默认的CA,这是蛮好的任何公共网站。

如果你有一个自签名的证书,您可以接受所有证书(有风险的,开放的人在这方面的中间人攻击)或创建自己的的TrustManagerFactory ,这是一个有点超出这个范围。

下面是一些code使用默认的CA为HTTPS POST电话:

 私人的InputStream的getInputStream(字符串urlStr,用户字符串,字符串密码)抛出IOException异常
{
    网址URL =新的URL(urlStr);
    HttpsURLConnection康恩=(HttpsURLConnection)url.openConnection();

    //创建SSL连接
    的SSLContext SC;
    SC = SSLContext.getInstance(TLS);
    sc.init(NULL,NULL,新java.security.SecureRandom中的());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    //使用这个,如果你需要的SSL认证
    串为userpass =用户+:+密码;
    字符串BASICAUTH =基本+ Base64.en codeToString(userpass.getBytes(),Base64.DEFAULT);
    conn.setRequestProperty(授权,BASICAUTH);

    //设置超时和方法
    conn.setReadTimeout(7000);
    conn.setConnectTimeout(7000);
    conn.setRequestMethod(POST);
    conn.setDoInput(真正的);

    //添加你要张贴在这里的任何数据

    conn.connect();
    返回conn.getInputStream();
}
 

要读取响应:

 字符串结果=新的String();
        InputStream的是=的getInputStream(urlStr,用户名,密码);
        的BufferedReader在=新的BufferedReader(新InputStreamReader的(是));
        字符串inputLine;
        而((inputLine = in.readLine())!= NULL){
            结果+ = inputLine;
        }
 

I want to do a HTTPS post method to send some data from my android app to my website.

I used HttpURLConnection first and it's working fine with my HTTP URL. My production website is on HTTPS and I want to send the same POST using HttpsURLConnection. Can someone help me use the class properly?

I found some source at this link:

KeyStore keyStore = ...;    
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");    
tmf.init(keyStore);

SSLContext context = SSLContext.getInstance("TLS");   
context.init(null, tmf.getTrustManagers(), null);

URL url = new URL("https://www.example.com/");   
HttpsURLConnection urlConnection = (HttpsURLConnection)
url.openConnection();   
urlConnection.setSSLSocketFactory(context.getSocketFactory());   
InputStream in = urlConnection.getInputStream();

What should be the value of KeyStore keyStore = ...;?

I tried sending the data using the same HttpURLConnection, but I am seeing some POST data is missed or in error.

I've tried the method from this question. I am pasting my code below

String urlParameters="dateTime=" + URLEncoder.encode(dateTime,"UTF-8")+
    "&mobileNum="+URLEncoder.encode(mobileNum,"UTF-8");

URL url = new URL(myurl);
HttpsURLConnection conn;
conn=(HttpsURLConnection)url.openConnection();

// Create the SSL connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setConnectTimeout(HTTP_CONNECT_TIME_OUT);
conn.setReadTimeout(HTTP_READ_TIME_OUT);

//set the output to true, indicating you are outputting(uploading) POST data
conn.setDoOutput(true);
//once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(urlParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(urlParameters);
out.close();

InputStream is = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
  response += inputLine;            
}                   

The error I am getting is below:

05-12 19:36:10.758: W/System.err(1123): java.io.FileNotFoundException: https://www.myurl.com/fms/test
05-12 19:36:10.758: W/System.err(1123):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
05-12 19:36:10.758: W/System.err(1123):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
05-12 19:36:10.758: W/System.err(1123):     at .httpRequest(SMSToDBService.java:490)
05-12 19:36:10.758: W/System.err(1123):     at com..access$0(SMSToDBService.java:424)
05-12 19:36:10.758: W/System.err(1123):     at com.$ChildThread$1.handleMessage(SMSToDBService.java:182)
05-12 19:36:10.758: W/System.err(1123):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 19:36:10.758: W/System.err(1123):     at android.os.Looper.loop(Looper.java:156)
05-12 19:36:10.758: W/System.err(1123):     at com.$ChildThread.run(SMSToDBService.java:303)

解决方案

You can use the default CAs that are defined in the android device, which is just fine for any public web.

If you have a self-signed certificate, you can either accept all certificates (risky, open to man-in-the-middle attacks) or create your own TrustManagerFactory, which is a bit out of this scope.

Here's some code to use the default CAs for a https POST call:

private InputStream getInputStream(String urlStr, String user, String password) throws IOException
{
    URL url = new URL(urlStr);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    // Create the SSL connection
    SSLContext sc;
    sc = SSLContext.getInstance("TLS");
    sc.init(null, null, new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Use this if you need SSL authentication
    String userpass = user + ":" + password;
    String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
    conn.setRequestProperty("Authorization", basicAuth);

    // set Timeout and method
    conn.setReadTimeout(7000);
    conn.setConnectTimeout(7000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // Add any data you wish to post here

    conn.connect();
    return conn.getInputStream();
}   

To read the response:

        String result = new String();
        InputStream is = getInputStream(urlStr, user, password);
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;            
        }       

这篇关于如何做到从Android的一个HTTPS POST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆