您的位置:首页 > 理论基础 > 计算机网络

Android HttpUrlConnection如何使用Https连接

2016-01-10 22:58 711 查看
一个小的demo

public String login(String uid, String password){
HttpsURLConnection connection=null;
try {
TrustManagerFactory tmf =  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore trusted = KeyStore.getInstance("PKCS12", "BC");
trusted.load(null, null);
InputStream in = getAssets().open("server.crt");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(in);
trusted.setCertificateEntry("trust", certificate);
in.close();

tmf.init(trusted);

TrustManager[] tms = tmf.getTrustManagers();

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null,tms,new SecureRandom());
URL url = new URL("https://127.0.0.1:8080/login");
connection= (HttpsURLConnection)url.openConnection();
connection.setSSLSocketFactory(sc.getSocketFactory());
connection.setRequestMethod("POST");
connection.setConnectTimeout(3000);//连接的超时时间
connection.setDoOutput(true);
connection.setDoInput(true);
//connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
OutputStreamWriter osw=new OutputStreamWriter(connection.getOutputStream());
osw.write("uid="+uid+"&pass_word="+password);
osw.flush();
osw.close();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb=new StringBuilder();
String aLine=null;
while ((aLine=reader.readLine())!=null){
sb.append(aLine).append("\n");
}
reader.close();
return sb.toString();
}catch (Exception e){
e.printStackTrace();
return e.getMessage();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android https