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调用请求
静态块设置证书:
- /**
- * 加载证书
- * */
- static {
- System.setProperty("javax.net.ssl.trustStore", "C:\\bmob.keystore");
- System.setProperty("javax.net.ssl.trustStorePassword", "password");
- }
POST方式:
- /**
- * 添加例子
- * @see <a href='http://docs.bmob.cn/restful/developdoc/index.html?menukey=develop_doc&key=develop_restful#index_添加数据'>例子</a>
- * */
- public static void add() throws Exception {
- //构建请求
- URL postUrl = new URL(ADD_URL);
- HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接
- con.setRequestMethod("POST");//post方式提交
- con.setDoOutput(true);//打开读写属性,默认均为false
- con.setDoInput(true);
- con.setUseCaches(false);//Post请求不能使用缓存
- con.setInstanceFollowRedirects(true);
- //添加头信息
- con.setRequestProperty("X-Bmob-Application-Id", APP_ID);
- con.setRequestProperty("X-Bmob-REST-API-Key", API_Key);
- con.setRequestProperty("Content-Type", "application/json");
- DataOutputStream out = new DataOutputStream(con.getOutputStream());
- //发送请求
- String data = "{\"name\":\"tom\"}";
- out.writeBytes(data);
- out.flush();
- out.close();
- //接收数据
- 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());
- }
GET方式:
- /**
- * 查询数据例子
- * @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(SELECT_URL);
- HttpsURLConnection con = (HttpsURLConnection) postUrl.openConnection();//打开连接
- con.setRequestMethod("GET");//get方式提交
- con.setDoInput(true);
- con.setInstanceFollowRedirects(true);
- //添加头信息
- con.setRequestProperty("X-Bmob-Application-Id", APP_ID);
- con.setRequestProperty("X-Bmob-REST-API-Key", API_Key);
- 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());
- }
其实与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 only
SSLConnectionSocketFactory 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.g
System.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());
}
}