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

java使用httpclient封装post请求和get的请求

在我们程序员生涯中,经常要复用代码,所以我们应该养成时常整理代码的好习惯,以下是我之前封装的httpclient的post和get请求所用的代码: package com.marco.com...
  • qq9808
  • qq9808
  • 2017-10-23 17:08:59
  • 13113

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

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

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

1. 配置及初始化HttpClient: private static final CloseableHttpClient httpclient; public static final Strin...
  • swordgirl2011
  • swordgirl2011
  • 2016-11-23 01:53:19
  • 4802

HttpClient通过Post方式发送Json数据

服务器用的是Springmvc,接口内容: [java] view plain copy  print? @ResponseBody   @Requ...
  • z69183787
  • z69183787
  • 2017-05-26 21:45:48
  • 3199

利用httpclient发送GET/POST请求

暂时只写post import com.alibaba.fastjson.JSON; import org.apache.commons.lang.StringUtils; import org.a...
  • u011649691
  • u011649691
  • 2018-03-26 18:25:39
  • 42

HttpClient 发送 POST 请求

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

利用HttpClient进行post或者get请求的工具类

  • 2017年08月03日 17:39
  • 12KB
  • 下载

httpClient发送http请求时组织post(put)数据

在组织POST数据时,用了UrlEncodedFormEntity()这个方法,但是后台报错,说是无法解析json内容。 按照本来的想法,向后台发送的是 json 格式的内容,里面有参数和值,供...
  • no_can_no_bb_
  • no_can_no_bb_
  • 2018-01-16 15:58:25
  • 235

使用HttpClient模拟POST请求

       HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议...
  • Evan_QB
  • Evan_QB
  • 2018-03-21 09:53:23
  • 22

httpclient4 post提交请求乱码问题解决

第一种: HttpPost post=new HttpPost(url); StringEntity content=new StringEntity(data, Charset.forName(...
  • shuaipu813
  • shuaipu813
  • 2016-08-29 14:46:00
  • 2615
收藏助手
不良信息举报
您举报文章:JAVA利用HttpClient进行POST请求(HTTPS)
举报原因:
原因补充:

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