JAVA利用HttpClient进行POST请求(HTTPS)

原创 2014年12月01日 23:06:31

目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用JQuery post进行请求。

但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而JQuery的post请求是不允许跨域的。

这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。

1.写一个SSLClient类,继承至HttpClient

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请求的类

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请求的测试代码

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();
	}
}

httpClient4.2的jar包下载路径:http://download.csdn.net/detail/hqmryang/4582440#comment

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

轻松把玩HttpClient之模拟post请求示例

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建...

Java使用HttpClient发送Get和Post请求

package com.taotao.httpClient.demo;import java.io.IOException; import java.io.UnsupportedEncodingExc...

HttpClient get和post请求的示例代码以及防乱码处理

请求别人发布的服务我们可能就会使用到HttpClient这个包,HttpClient就是一个支持 HTTP 协议的客户端编程工具包,用来模拟浏览器请求。 乱码解决方法: 就是给HttpGet对象或者H...

掌握HttpClient类的GET和POST请求访问服务器步骤!

HttpClient 是HttpConnection的增强  (网络访问) HttpClient需要导入第三方库的jar包: 在当前工程下新建以文件夹,用来存放第三个的jar文件,比如叫做:l...

HttpClient 发送 POST 请求

HttpClient 发送 POST 请求 HttpClientBuilder用于创建CloseableHttpClient实例。 在 HttpClient 新的版本中, AbstractHttpC...
  • tajun77
  • tajun77
  • 2016年05月08日 18:12
  • 2733

HttpClient通过Post方式发送Json数据

服务器用的是Springmvc,接口内容: @ResponseBody @RequestMapping(value="/order",method=RequestMethod.POST) pu...

HttpClient发送Get、Post请求简单实践

1. 配置及初始化HttpClient: private static final CloseableHttpClient httpclient; public static final Strin...

HttpClient通过Post方式发送Json数据

服务器用的是Springmvc,接口内容: [java] view plain copy  print? @ResponseBody   @Requ...

HTTPClient模块的HttpGet和HttpPost

Android SDK集成了Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是...

java apache commons HttpClient发送get和post请求的学习整理

java apache commons HttpClient发送get和post请求的学习整理,代码下载地址:http://www.zuidaima.com/share/175406598340915...
  • yaerfeng
  • yaerfeng
  • 2014年04月24日 10:50
  • 47508
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:JAVA利用HttpClient进行POST请求(HTTPS)
举报原因:
原因补充:

(最多只允许输入30个字)