java模拟https请求

来源:互联网 发布:怎么在淘宝头条上发帖 编辑:程序博客网 时间:2024/06/01 09:27

http://blog.csdn.net/hzaccp3/article/details/42927093

最近一个APP要用到云存储,比较了几个云空间后,最后选择了Bmob(http://www.bmob.cn/),Bmob功能不少,还提供各种API,免费。


由于我的APP较小,业务也简单,所以直接用Bmob提供的Rest API。

Bmob的Rest API是https协议的,所以我的想法是:先导出Bmob的证书,用java的keyTool工具制成证书库(keystore),再用HttpsURLConnection与Bmob服务器沟通。

下面为具体步骤:

 1:导出证书
用IE的证书工具可以将网站的证书导出。打开网页,查看网页的属性页,属性页右下角可以找到证书,最后将证书【复制到文件】。



由于Java的keyTool工具不能导入P7B格式的证书,所以在导入向导中,我选择Base64编码的CER证书:


最终得到证书文件:


 2:创建证书库并导入证书
用java的keyTool工具,执行下列命令,得到bmob.keystore证书库文件:

--生成证书库文件
keytool -genkey -alias bmob.keystore -keyalg RSA -validity 100000 -keystore bmob.keystore

--导入Der/Cer证书
keytool -import -file bmob.cer -keystore bmob.keystore

注:将bmob.cer文件导入证书库时,最好与证书库同一目录

 3:java调用请求
静态块设置证书:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 加载证书 
  3.  * */  
  4. static {  
  5.     System.setProperty("javax.net.ssl.trustStore""C:\\bmob.keystore");  
  6.     System.setProperty("javax.net.ssl.trustStorePassword""password");  
  7. }  

POST方式:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 添加例子 
  3.  * @see <a href='http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_添加数据'>例子</a> 
  4.  * */  
  5. public static void add() throws Exception {  
  6.     //构建请求  
  7.     URL postUrl = new URL(ADD_URL);  
  8.   
  9.     HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接   
  10.     con.setRequestMethod("POST");//post方式提交  
  11.   
  12.     con.setDoOutput(true);//打开读写属性,默认均为false   
  13.     con.setDoInput(true);  
  14.     con.setUseCaches(false);//Post请求不能使用缓存   
  15.     con.setInstanceFollowRedirects(true);  
  16.   
  17.     //添加头信息  
  18.     con.setRequestProperty("X-Bmob-Application-Id", APP_ID);  
  19.     con.setRequestProperty("X-Bmob-REST-API-Key", API_Key);  
  20.     con.setRequestProperty("Content-Type""application/json");  
  21.   
  22.     DataOutputStream out = new DataOutputStream(con.getOutputStream());  
  23.   
  24.     //发送请求  
  25.     String data = "{\"name\":\"tom\"}";  
  26.     out.writeBytes(data);  
  27.     out.flush();  
  28.     out.close();  
  29.   
  30.     //接收数据  
  31.     BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));  
  32.     String line;  
  33.     StringBuffer responseText = new StringBuffer();  
  34.     while ((line = reader.readLine()) != null) {  
  35.         responseText.append(line).append("\r\n");  
  36.     }  
  37.     reader.close();  
  38.     con.disconnect();  
  39.     System.out.println(responseText.toString());  
  40. }  

GET方式:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * 查询数据例子 
  3.  * @see <a target=_blank href="http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_查询数据">例子</a> 
  4.  * */  
  5. public static void select() throws Exception {  
  6.     //构建请求  
  7.     URL postUrl = new URL(SELECT_URL);  
  8.   
  9.     HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接   
  10.     con.setRequestMethod("GET");//get方式提交  
  11.     con.setDoInput(true);  
  12.     con.setInstanceFollowRedirects(true);  
  13.   
  14.     //添加头信息  
  15.     con.setRequestProperty("X-Bmob-Application-Id", APP_ID);  
  16.     con.setRequestProperty("X-Bmob-REST-API-Key", API_Key);  
  17.     con.setRequestProperty("Content-Type""application/json");  
  18.   
  19.     //接收数据  
  20.     BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));  
  21.     String line;  
  22.     StringBuffer responseText = new StringBuffer();  
  23.     while ((line = reader.readLine()) != null) {  
  24.         responseText.append(line).append("\r\n");  
  25.     }  
  26.     reader.close();  
  27.     con.disconnect();  
  28.     System.out.println(responseText.toString());  
  29. }  

其实与http请求差不多,只是多了证书制作部分。


详解demo

使用httpclient框架

/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation.  For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */package org.apache.http.examples.client;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.security.KeyStore;import javax.net.ssl.SSLContext;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.TrustSelfSignedStrategy;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;/** * This example demonstrates how to create secure connections with a custom SSL * context. */public class Bmob {public final static void main(String[] args) throws Exception {KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());FileInputStream instream = new FileInputStream(new File("d:\\bmob.keystore"));try {trustStore.load(instream, "000000".toCharArray());} finally {instream.close();}SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();// Allow TLSv1 protocol onlySSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();try {HttpGet httpget = new HttpGet("https://api.bmob.cn/1/classes/GameScore");httpget.addHeader("X-Bmob-Application-Id","e2b1e794245f81b620161f0713d72dce");httpget.addHeader("X-Bmob-REST-API-Key","30f1a9fe9ac5f18312ffb23f8b295fc7");//httpget.gSystem.out.println("executing request" + httpget.getRequestLine());CloseableHttpResponse response = httpclient.execute(httpget);try {HttpEntity entity = response.getEntity();System.out.println("----------------------------------------");System.out.println(response.getStatusLine());if (entity != null) {System.out.println("Response content length: "+ entity.getContentLength());System.out.println(EntityUtils.toString(entity));}EntityUtils.consume(entity);} finally {response.close();}} finally {httpclient.close();}}}

使用原始的java

import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URL;import javax.net.ssl.HttpsURLConnection;public class Test {/** * 加载证书 * */static {System.out.println("static");System.setProperty("javax.net.ssl.trustStore", "d:\\bmob.keystore");System.setProperty("javax.net.ssl.trustStorePassword", "000000");}/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {//System.out.println("fdsf");select();}/** * 查询数据例子 * @see <a target=_blank href="http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_查询数据">例子</a> * */public static void select() throws Exception {//构建请求URL postUrl = new URL("https://api.bmob.cn/1/classes/GameScore");HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接 con.setRequestMethod("GET");//get方式提交con.setDoInput(true);con.setInstanceFollowRedirects(true);//添加头信息con.setRequestProperty("X-Bmob-Application-Id", "e2b1e794245f81b620161f0713d72dce");con.setRequestProperty("X-Bmob-REST-API-Key", "30f1a9fe9ac5f18312ffb23f8b295fc7");con.setRequestProperty("Content-Type", "application/json");//接收数据BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));String line;StringBuffer responseText = new StringBuffer();while ((line = reader.readLine()) != null) {responseText.append(line).append("\r\n");}reader.close();con.disconnect();System.out.println(responseText.toString());}}






0 0