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调用请求
静态块设置证书:
- /**
- * 加载证书
- * */
- 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 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
- java模拟https请求
- java模拟https请求
- java模拟https请求
- java 通过Httpclient模拟https Post 请求,实现双向认证
- php curl模拟https请求
- fiddler抓取https请求和jmeter模拟https请求
- Java https请求 HttpsURLConnection
- java 实现https请求
- java 实现https请求
- java Https的请求
- java 发送 https请求
- java 实现https请求
- Java https请求 HttpsURLConnection
- JAVA请求HTTPS协议
- java访问https请求
- java发送https请求
- JAVA请求HTTPS协议
- java 实现https请求
- centos 新增ftp用户
- Android应用程序窗口(Activity)的视图对象(View)的创建过程分析
- BLAST-动态规划算法
- 周期串(Periodic Strings)
- It looks like git-am is in progress. Cannot rebase.
- java模拟https请求
- linux下使用最简单的命令打开各类文件
- 遗传算法 简单函数优化
- Shell学习一(基础知识)
- pb 直连sql anywhere数据库
- POJ 1852 Ants (思维技巧 + 贪心)
- c算法 ->递归函数
- [jenkins][git]jenkins CI初探
- 遗传算法求解迷宫问题的matlab代码——greatji_1994