Android https Request(加密通道传参数)2014-10-12 13:36:22

( 32人已投票,[高质量] )
分享:
31.3K

传统的Android普通的HTTP访问方式无法适用于HTTPS访问方式。

因为HTTPS为走加密通道,是需要走鉴权过程。

下面直接上处理方法代码了。

Android普通的接口访问可以用POST或GET方式(两种方式实质上无区别):

private void processInternetLogin()
   {
    String uriAPI = "http://test.com/index.php";
    String strName ="test";
    String strPwd = "1234";
    String strRet = "";
    try
    {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    HttpPost httpost = new HttpPost(uriAPI);
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("name", strName)); 
    nvps.add(new BasicNameValuePair("pwd", strPwd)); 
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    response = httpclient.execute(httpost);
    HttpEntity entity = response.getEntity();
    //entity = response.getEntity();
    Log.d(TAG, "HTTP POST getStatusLine: " + response.getStatusLine());
    /* HTML POST response BODY */
    strRet = EntityUtils.toString(entity);
    Log.i(TAG, strRet);
    strRet = strRet.trim().toLowerCase();
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (entity != null)
     {
     entity.consumeContent();
     }
    Log.d(TAG, "HTTP POST Initialize of cookies."); 
    cookies = httpclient.getCookieStore().getCookies(); 
    if (cookies.isEmpty())
     {
      Log.d(TAG, "HTTP POST Cookie not found.");
      Log.i(TAG, entity.toString());
     }
     else
     {
     for (int i = 0; i < cookies.size(); i++)
     {
      Log.d(TAG, "HTTP POST Found Cookie: " + cookies.get(i).toString()); 
      } 
      }    
    System.out.println("result:"+strRet);//返回的结果!
    }
    catch(Exception e)
    {
    e.printStackTrace();    
}
}


普通请求是可以这样做,但是对于https方式的清求,会提示不安全的证书,或是handshark错误,一堆错误造成请求失败。

整个网络都在说安全验证通信这块内容,对于传参数到鲜有说明,特添加包含传参实现

由于没有常用的setEntity方法

由于https是走加密通道,所以应该用以下的处理方式,看清楚传参部分,自由扩展。

private void GetHttps(){
String https = "https://test/test.php";//https uri
String query = "name=abc&pass=123";
byte[] entitydata = query.getBytes();
try{
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new MyTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
 HttpsURLConnection conn = (HttpsURLConnection)new URL(https).openConnection();
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));        
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//建好连接了,把output数据flush过去,(也可以通过此方法传文件流的好像)
OutputStream outStream = conn.getOutputStream();
outStream.write(entitydata);
outStream.flush();
outStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
System.out.println("TEST::"+sb.toString());
//经测试,此处显示了远端返回的测试字符串"Got Name is:abc and pass is:123"
}catch(Exception e){
 Log.e(this.getClass().getName(), e.getMessage());
}
}
private class MyHostnameVerifier implements HostnameVerifier{
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
}
                                                                                                                                                                                                        
private class MyTrustManager implements X509TrustManager{
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {
// TODO Auto-generated method stub
}
                                                                                                                                                                                                        
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
 }    
}


服务器端测试代码://test.php

$name = isset($_REQUEST["name"])?$_REQUEST["name"]:"Sorry,No Data.";
$pass = isset($_REQUEST["pass"])?$_REQUEST["pass"]:"Sorry,No Data.";
echo "Got Name is:".$name." and pass is:".$pass;


这样参数就发送成功了(没有实测的内容一般我不发出来)

全都用上时,跟据提示默认选择导入一些头文件,有两个不知道哪个的时候选第一个

可自由深入发展,例如,传送Json数据,xml解析等~







头像

snowcoal
  • Android
  • Https
  • 加密通道传参

收藏到我的私密空间

标题:Android https Request(加密通道传参数)

作者:花花世界

你暂未登录,请登录后才可收藏至您的私密空间 确认取消
雪炭网

键盘操作 更便捷 -雪炭网雪中送炭-乐趣无限

如果本站的内容有幸帮助到了您,建议您了解一下当页的广告内容哦,我们的进步离不开您的支持,Thank you~