- 浏览: 15075 次
- 性别:
- 来自: 上海
文章分类
最新评论
目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求。
但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的。
这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
1.写一个SSLClient类,继承至HttpClient
[java] view plain
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
2.写一个利用HttpClient发送post请求的类
[java] view plain
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpClientUtil {
public String doPost(String url,Map<String,String> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
3.调用post请求的测试代码
[java] view plain
import java.util.HashMap;
import java.util.Map;
//对接口进行测试
public class TestMain {
private String url = "https://192.168.1.101/";
private String charset = "utf-8";
private HttpClientUtil httpClientUtil = null;
public TestMain(){
httpClientUtil = new HttpClientUtil();
}
public void test(){
String httpOrgCreateTest = url + "httpOrg/create";
Map<String,String> createMap = new HashMap<String,String>();
createMap.put("authuser","*****");
createMap.put("authpass","*****");
createMap.put("orgkey","****");
createMap.put("orgname","****");
String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
System.out.println("result:"+httpOrgCreateTestRtn);
}
public static void main(String[] args){
TestMain main = new TestMain();
main.test();
}
}
4.GET的请求方式
[java] view plain copy 在CODE上查看代码片派生到我的代码片
/**
* 发送get请求
* @param url 链接地址
* @param charset 字符编码,若为null则默认utf-8
* @return
*/
public String doGet(String url,String charset){
if(null == charset){
charset = "utf-8";
}
HttpClient httpClient = null;
HttpGet httpGet= null;
String result = null;
try {
httpClient = new SSLClient();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
需要:httpcore-4.3.3.jar,
httpcore-4.0.1.jar 不支持SSLClient()
httpClient4.2的jar包下载路径:http://download.csdn.net/detail/hqmryang/4582440#comment
但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的。
这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
1.写一个SSLClient类,继承至HttpClient
[java] view plain
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
2.写一个利用HttpClient发送post请求的类
[java] view plain
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpClientUtil {
public String doPost(String url,Map<String,String> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
3.调用post请求的测试代码
[java] view plain
import java.util.HashMap;
import java.util.Map;
//对接口进行测试
public class TestMain {
private String url = "https://192.168.1.101/";
private String charset = "utf-8";
private HttpClientUtil httpClientUtil = null;
public TestMain(){
httpClientUtil = new HttpClientUtil();
}
public void test(){
String httpOrgCreateTest = url + "httpOrg/create";
Map<String,String> createMap = new HashMap<String,String>();
createMap.put("authuser","*****");
createMap.put("authpass","*****");
createMap.put("orgkey","****");
createMap.put("orgname","****");
String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
System.out.println("result:"+httpOrgCreateTestRtn);
}
public static void main(String[] args){
TestMain main = new TestMain();
main.test();
}
}
4.GET的请求方式
[java] view plain copy 在CODE上查看代码片派生到我的代码片
/**
* 发送get请求
* @param url 链接地址
* @param charset 字符编码,若为null则默认utf-8
* @return
*/
public String doGet(String url,String charset){
if(null == charset){
charset = "utf-8";
}
HttpClient httpClient = null;
HttpGet httpGet= null;
String result = null;
try {
httpClient = new SSLClient();
httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
需要:httpcore-4.3.3.jar,
httpcore-4.0.1.jar 不支持SSLClient()
httpClient4.2的jar包下载路径:http://download.csdn.net/detail/hqmryang/4582440#comment
发表评论
-
Java面试题全集(下)
2017-07-19 17:47 0这部分主要是开源Java EE框架方面的内容,包括hibe ... -
Java面试题全集(中)
2017-07-19 17:44 415这部分主要是与Java Web和Web Service相关的 ... -
Java面试题全集(上)
2017-07-19 17:39 529转自:http://blog.csdn.net/jackf ... -
遍历Map的四种方法
2017-04-18 11:04 430public static void main(Strin ... -
js String 转int
2017-04-10 16:08 639var str='1250' ; alert( Number ... -
Struts2拦截器、拦截器栈(Interceptor Stack)、全局拦截器与方法拦截器
2017-03-22 14:57 357[img][/img] http://blog.csdn.n ... -
Java虚拟机类加载机制
2017-03-22 11:23 477Java程序运行于Java虚拟机之上,JVM屏蔽了底层细节,使 ... -
国外程序员整理的Java资源大全
2017-02-10 16:49 436PS: 引用 http://www.open-open.com ... -
获取项目的各种路径
2016-10-08 17:42 299@Action(name="FddSi ... -
Java关键字final、static使用总结
2016-09-20 10:35 268ava关键字final、static使用总结 一、fina ...
相关推荐
"JAVA利用HttpClient进行POST请求(HTTPS)" JAVA HttpClient是Apache软件基金会提供的一个开源实现HTTP客户端的Java库,能够帮助开发者轻松地与HTTP服务器进行交互。在实际项目中,我们经常需要使用HttpClient来发送...
### Java HttpClient 发送GET请求和带有表单参数的POST请求详解 #### 一、概述 在Java编程中,处理HTTP请求是一项常见的需求,特别是在与Web服务进行交互时。Apache HttpClient库提供了一种强大的方法来执行HTTP...
本实例将介绍如何使用HttpClient进行POST请求,特别是针对HTTPS的请求,以避免证书校验过程。 首先,我们需要创建一个自定义的SSLClient类,这个类继承自DefaultHttpClient。在SSLClient类中,我们将重写SSL证书的...
总的来说,使用Java的HttpClient进行HTTPS接口调用涉及到配置SSL上下文、初始化HttpClient、创建请求对象以及处理响应。了解这些知识点对于开发安全的、能够与HTTPS服务进行通信的Java应用程序至关重要。通过实践和...
httpclient的用法,发送get请求和post请求,设置header
接下来,我们讨论如何使用HttpClient进行GET请求。GET请求通常用于获取资源,不涉及请求体: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(...
利用httpclient-4.3.1.jar、httpcore-4.3.jar包,很简单的用java实现httpget和httppost请求。
GET请求用于从服务器获取资源,其使用方式比POST简单: 1. **创建HttpGet请求**:使用`HttpGet`类创建一个请求对象,并设置请求URL。 2. **执行请求**:同POST请求,通过HttpClient的`execute()`方法发送请求。 3. ...
在IT行业中,网络通信是应用程序之间交互的基础,而HTTP(超文本传输协议)和HTTPS(安全超文本传输协议)则是...理解并掌握HttpClientUtil的工作原理和使用方法,对于任何需要进行网络通信的Java项目都是至关重要的。
在Java编程中,发送HTTP和HTTPS请求是常见的网络通信任务,尤其在开发Web服务客户端或者进行API测试时。本文将详细讲解如何使用Java发送GET和POST请求,以及涉及的HTTPS安全连接。 首先,理解HTTP和HTTPS的区别至关...
这个压缩包可能包含了实现HTTP GET和POST请求所需的jar包以及示例代码,帮助开发者理解如何使用HttpClient进行网络通信。下面将详细介绍HttpClient库,HTTP请求的基本概念,以及GET和POST方法的差异。 HttpClient是...
httpclient get/post请求工具类(map参数封装),方便调用
同时,通过阅读如"HttpClient发送get请求和post请求"这样的博客,你可以获取更多关于HttpClient实战中的技巧和最佳实践。在提供的压缩包文件中,`test-demo`和`httpclient-demo`可能包含了这些示例的源码,供你...
"JAVA利用HttpClient进行HTTPS接口调用的方法" 知识点1:HttpClient的基本概念 HttpClient是一个开放源代码的Java库,用于提供高效、灵活和可扩展的HTTP客户端解决方案。HttpClient支持HTTP/1.1和HTTP/2.0协议,...
本篇将详细介绍如何使用HttpClient发送HTTP请求,包括POST和GET方法,同时提供相关的jar包依赖以及Java代码示例,并对关键代码进行注解解释。 一、HttpClient库的引入 在Java项目中,首先需要添加HttpClient的jar包...
以下是一个简单的GET请求示例: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com"); CloseableHttpResponse response = httpClient....
JAVA使用HttpClient模拟浏览器GET、POST请求 在本文中,我们将介绍如何使用Apache Commons HttpClient库来模拟浏览器的GET和POST请求。HttpClient库是一个开放源码的项目,是Apache Commons项目的一部分,旨在简化...