Java java httpclient4.5 进行http,https通过SSL安全验证跳过,封装接口请求 get,post(formdata,json)封装,文件上传下载

摘要:
url.contains("=")){if(parameters!=null&&parameters.size()˃0){for(Map.Entryentry:parameters.entrySet()){Stringk=entry.getKey().toString();Stringv=entry.getValue().toString();formData.add(newBasicNameValuePair(k,v));}}urlencoded=EntityUtils.toString(newUrlEncodedFormEntity(formData,Consts.UTF_8));if(basicUrl.contains("?")){get=newHttpGet(basicUrl+urlencoded);if(headers!=null&&headers.size()˃0){for(Map.Entryentry:headers.entrySet()){get.setHeader(entry.getKey().toString(),entry.getValue().toString());}}else{get.setHeader(null);}response=httpclient.execute(get);entity=response.getEntity();result=EntityUtils.toString(entity,"UTF-8");returnresult;}else{//无?get=newHttpGet(basicUrl+"?"+urlencoded);if(headers!
package api;

import java.util.*;
import java.net.URI;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
import com.sun.xml.internal.stream.Entity;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import java.io.*;
import java.io.File;  
import org.apache.http.entity.mime.MultipartEntityBuilder;

public class TestHttpClient {
	static HttpPost post;
	static HttpResponse response;
	static HttpGet get;
	static HttpEntity entity;
//	private static Logger logger = Logger.getLogger(TestHttpClient.class);
	 
	
	//ssl安全跳过
	public static CloseableHttpClient getignoreSSLClient() {
		CloseableHttpClient client =null;
		try {
			SSLContext sslContext=SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
				
				@Override
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			}).build();
			client=HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return client;
	}
	
	//
	public static String getrequest(String url,Map<Object, Object> parameters,Map<Object,Object> headers){
		String basicUrl=url;
		String result=null;
		String urlencoded=null;
//		CloseableHttpClient httpclient=HttpClients.createDefault();
		CloseableHttpClient httpclient=getignoreSSLClient();
		List<NameValuePair> formData=new ArrayList<NameValuePair>();
		
		try {
			//参数分离
			if(!url.contains("=")) {
				if(parameters !=null && parameters.size()>0) {
					for(Map.Entry<Object,Object> entry:parameters.entrySet()) {
						String k =entry.getKey().toString();
						String v=entry.getValue().toString();
						formData.add(new BasicNameValuePair(k, v));	
					}
				}
				urlencoded =EntityUtils.toString(new UrlEncodedFormEntity(formData, Consts.UTF_8));
				if(basicUrl.contains("?")) {
					
					get=new HttpGet(basicUrl+urlencoded);
					if(headers !=null && headers.size()>0) {
						for(Map.Entry<Object, Object> entry:headers.entrySet()) {
							get.setHeader(entry.getKey().toString(),entry.getValue().toString());
						}
					}else {
						get.setHeader(null);
					}
					response=httpclient.execute(get);
					entity=response.getEntity();
					result=EntityUtils.toString(entity,"UTF-8");
					return result;
				}else {
					//无?
					get=new HttpGet(basicUrl+"?"+urlencoded);
					if(headers !=null && headers.size()>0) {
						for(Map.Entry<Object, Object> entry:headers.entrySet()) {
							get.setHeader(entry.getKey().toString(),entry.getValue().toString());
						}
					}else {
						get.setHeader(null);
					}
					response=httpclient.execute(get);
					entity=response.getEntity();
					result=EntityUtils.toString(entity,"UTF-8");
					return result;
				}	
			}else {
				
				//纯url
				get=new HttpGet(basicUrl);
				response=httpclient.execute(get);
				entity=response.getEntity();
				result=EntityUtils.toString(entity,"UTF-8");
				return result;
			}			
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null) {
					httpclient.close();
				}
			}catch(IOException e) {
			e.printStackTrace();
			}
		}
		return result;
	}
	
	//postformData
	public static String postformData(String url,Map<Object, Object> body,Map<Object, Object> headers){
		String basicUrl=url;
		String result=null;

		CloseableHttpClient httpclient=getignoreSSLClient();
		List<NameValuePair> formData=new ArrayList<NameValuePair>();
		try {	
			   post =new HttpPost();
			   post.setURI(new URI(basicUrl));
			   //上面可以直接用post = new HttpPost(url)代替
	           for (Iterator iter = body.keySet().iterator(); iter.hasNext();) {
	    			String k = (String) iter.next();
	    			String v = String.valueOf(body.get(k));
	    			formData.add(new BasicNameValuePair(k, v));
	    			System.out.println("构造参数完毕");
	    		}
				if(headers !=null && headers.size()>0) {
					for(Map.Entry<Object, Object> entry:headers.entrySet()) {
						post.setHeader(entry.getKey().toString(),entry.getValue().toString());
					}
				}else {
					post.setHeader(null);
					//header设置完毕
				}
				post.setEntity(new UrlEncodedFormEntity(formData,Consts.UTF_8));
	            response = httpclient.execute(post);
	            entity  =response.getEntity();
	            result=EntityUtils.toString(entity, "UTF-8");
	            int errorCode= response.getStatusLine().getStatusCode();
	            if(String.valueOf(errorCode)!=null) {
	            		return result;
	            }else {
	            	result=null;
	            	return result;
	            }
	            	
		}catch(Exception e ) {
			e.printStackTrace();
		}finally {
			try {
					if(httpclient!=null) {
						httpclient.close();
					}
				}catch(Exception e) {
					e.printStackTrace();
				}	
		}
		return result;
	}
	
	// postJson 
	public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object> headers){
		
		String basicUrl=url;
		String result=null;
		post =new HttpPost(basicUrl);
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
			if(headers !=null && headers.size()>0) {
				for(Map.Entry<Object, Object> entry:headers.entrySet()) {
					post.setHeader(entry.getKey().toString(),entry.getValue().toString());
				}
			}else {
				post.setHeader(null);
				//header设置完毕
			}
			//body转string,处理entity传入httpEntity
			StringEntity newEntity=new StringEntity(body.toString(),"utf-8");
			post.setEntity(newEntity);;
			response=httpclient.execute(post);
			int errorCode =response.getStatusLine().getStatusCode();
			if(String.valueOf(errorCode) !=null) {
				entity =response.getEntity();
				result=EntityUtils.toString(entity, "UTF-8");
				return result;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null) {
					httpclient.close();
				}
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}	
	
	// download file ,两个都要带路径
	public static void downloadfile(String url,String localfileName,String remotefileName) {
		FileOutputStream output = null;
		InputStream in = null;
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
		get=new HttpGet(url);
		get.addHeader("fileName",remotefileName );
		response=httpclient.execute(get);
		entity =response.getEntity();
		in = entity.getContent();
		long length = entity.getContentLength();
		if (length <= 0) {
			return;
		}
		File localfile = new File(localfileName);
		
		if(! localfile.exists()) {
			localfile.createNewFile();
		}
		output=new FileOutputStream(localfile);
	    byte[] buffer = new byte[4096];
	    int readLength = 0;
	    while ((readLength=in.read(buffer)) > 0) {
	    byte[] bytes = new byte[readLength];
	    System.arraycopy(buffer, 0, bytes, 0, readLength);
	    output.write(bytes);
	                 }         
	    output.flush();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(in !=null) {
					in.close();
				}
				if(output !=null) {
					output.close();
				}
			}catch (IOException e) {
				e.printStackTrace();
			} 
		}		
	}
	
	// uploadfile 
	public static void uploadfile(String localfilepath,String url) {
		
		
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
		post = new HttpPost(url);
		FileBody bin=new FileBody(new File(localfilepath));
		HttpEntity reentity= MultipartEntityBuilder.create().addPart("bin",bin).build();
		post.setEntity(entity);
		response=httpclient.execute(post);
		entity=response.getEntity();
		if(entity!=null) {
			// length entity.getContentLength();
			String content=EntityUtils.toString(entity,"utf-8");
			EntityUtils.consume(entity);
		}
		
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null ) {
					httpclient.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
			
	}
	
	
}

免责声明:文章转载自《Java java httpclient4.5 进行http,https通过SSL安全验证跳过,封装接口请求 get,post(formdata,json)封装,文件上传下载》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇axios的基本用法与并发请求MySQL索引与锁笔记下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Hive笔记--配置以及遇到的问题

ubuntu安装mysql http://www.2cto.com/database/201401/273423.htmlHive安装: http://www.aboutyun.com/forum.php?mod=viewthread&tid=6902 (aboutyun)http://wangqiaowqo.iteye.com/blog/1618...

Java中实现Http请求并获取响应数据

目录 前言 方式一:功能实现类 java.net.HttpURLConnection 方式二:功能实现类 org.apache.http.client.methods.HttpGet 前言 在演示的功能代码中使用的请求http地址为:http://timor.tech/api/holiday/year/ 接口说明:获取指定年份或年月份的所有节...

CVE-2019-0232漏洞复现

CVE-2019-0232 1、漏洞简介 CVE-2019-0232漏洞是由于Tmocat CGI将命令行参数传递给Windows程序的方式存在错误,使得CHIServler被命令注入影响。 该漏洞只影响Windows平台,要求启用了CGIServlet和enableCmdLineArguments参数。但是CGIServlet和enableCmdLine...

Mac下PHP开发环境的搭建(转载)

一、首先Mac OS自带Apache,只需要启动Apache就行。 打开终端,输入命令:sudo apachectl start : 介绍几个Apache的常用命令 //启动Apache服务 sudoapachectl start //重启Apache服务 sudoapachectl restart //停止Apache服务 sudoapach...

Linux下Apache配置HTTPS功能

Apache配置HTTPS功能转https://www.cnblogs.com/liaojiafa/p/6028816.html 一、yum 安装openssl和openssl-devel,httpd-devel 二、生成证书(也可以从公司的证书颁发机构获取): #建立服务器密钥 openssl genrsa -des3 1024 > /...

Eclipse环境搭建并且运行wordcount程序

一、安装Hadoop插件   1. 所需环境 hadoop2.0伪分布式环境平台正常运行 所需压缩包:eclipse-jee-luna-SR2-linux-gtk-x86_64.tar.gz 在Linux环境下运行的eclipse软件压缩包,解压后文件名为eclipsehadoop2x-eclipse-plugin-master.zip 在eclipse中...