HttpClientUtil工具类

pom.xml需要的jar包

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.5.5</version>
 </dependency>
 <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>

需要导入的包


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.lang.StringUtils;

import org.apache.http.HttpEntity;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.example.demo.image.entity.NameToDefectsPo;
import com.example.demo.image.entity.User;

public class HttpClientUtil {
	
	public void doGet(String s) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		HttpGet httpGet=new HttpGet(s);
		
	//	HttpGet httpGet=new HttpGet("http://localhost:27027/bucket_backup/get/{bucket}/{path}");
	//	HttpGet httpGet1=new HttpGet("http://localhost:27027/bucket_backup/get/id");
	
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Get请求
			response = httpClient.execute(httpGet);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		
	}

	public void doGetParam(String s) {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		StringBuffer params=new StringBuffer();
		// 创建Get请求
			
		try {
			// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
			params.append("name=" + URLEncoder.encode("&", "utf-8"));
			params.append("liunn");
			params.append("age=24");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		HttpGet httpGet = new HttpGet("http://localhost:12345/doGetControllerTwo" + "?" + params);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 配置信息
			RequestConfig requestConfig = RequestConfig.custom()
					// 设置连接超时时间(单位毫秒)
					.setConnectTimeout(5000)
					// 设置请求超时时间(单位毫秒)
					.setConnectionRequestTimeout(5000)
					// socket读写超时时间(单位毫秒)
					.setSocketTimeout(5000)
					// 设置是否允许重定向(默认为true)
					.setRedirectsEnabled(true).build();
 
			// 将上面的配置信息 运用到这个Get请求里
			httpGet.setConfig(requestConfig);
 
			// 由客户端执行(发送)Get请求
			response = httpClient.execute(httpGet);
 
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void doGetTestWayTwo() {
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 参数
		URI uri = null;
		try {
			// 将参数放入键值对类NameValuePair中,再放入集合中
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("name", "&"));
			params.add(new BasicNameValuePair("age", "18"));
			// 设置uri信息,并将参数集合放入uri;
			// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
			uri = new URIBuilder().setScheme("http").setHost("localhost")
					              .setPort(12345).setPath("/doGetControllerTwo")
					              .setParameters(params).build();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
		// 创建Get请求
		HttpGet httpGet = new HttpGet(uri);
 
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 配置信息
			RequestConfig requestConfig = RequestConfig.custom()
					// 设置连接超时时间(单位毫秒)
					.setConnectTimeout(5000)
					// 设置请求超时时间(单位毫秒)
					.setConnectionRequestTimeout(5000)
					// socket读写超时时间(单位毫秒)
					.setSocketTimeout(5000)
					// 设置是否允许重定向(默认为true)
					.setRedirectsEnabled(true).build();
 
			// 将上面的配置信息 运用到这个Get请求里
			httpGet.setConfig(requestConfig);
 
			// 由客户端执行(发送)Get请求
			response = httpClient.execute(httpGet);
 
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	public String doPostTestOne(String url) {
		 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		String responseEntityToStrong = null ;
		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				responseEntityToStrong=EntityUtils.toString(responseEntity);
				System.out.println("响应内容为:" + responseEntityToStrong);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return responseEntityToStrong;
	}

	
	public void doPostTestFour() {
		 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 参数
		StringBuffer params = new StringBuffer();
		try {
			// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
			params.append("name=" + URLEncoder.encode("&", "utf-8"));
			params.append("&");
			params.append("age=24");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
 
		// 创建Post请求
		HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerFour" + "?" + params);
 
		// 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		}

	public void doPostTestTwo(String url,NameToDefectsPo nameToDefects) {
		 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 创建Post请求
		//HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
		HttpPost httpPost = new HttpPost(url);
		/*
		 * User user = new User(); user.setName("潘晓婷"); user.setPassword("11111");;
		 * user.setId(11111); user.setDesc("nishuo");
		 */
		// 我这里利用阿里的fastjson,将Object转换为json字符串;
		// (需要导入com.alibaba.fastjson.JSON包)
		String jsonString = JSON.toJSONString(nameToDefects); 
		StringEntity entity = new StringEntity(jsonString, "UTF-8");
 
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
 
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void doPostTestThree() {
		 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 创建Post请求
		// 参数
		URI uri = null;
		try {
			// 将参数放入键值对类NameValuePair中,再放入集合中
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("flag", "4"));
			params.add(new BasicNameValuePair("meaning", "这是什么鬼?"));
			// 设置uri信息,并将参数集合放入uri;
			// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
			uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(12345)
					.setPath("/doPostControllerThree").setParameters(params).build();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
 
		HttpPost httpPost = new HttpPost(uri);
		// HttpPost httpPost = new
		// HttpPost("http://localhost:12345/doPostControllerThree1");
 
		// 创建user参数
		User user = new User();
		user.setName("潘晓婷");
		user.setPassword("11111");;
		user.setId(11111);
		user.setDesc("nishuo");
 
		// 将user对象转换为json字符串,并放入entity中
		StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
 
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
 
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void upload() {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");
 
			FileEntity bin = new FileEntity(new File("F:\\image\\sendpix0.jpg"));
			
			//  StringBody comment = new StringBody("A binary file of some kind",
		//	  ContentType.TEXT_PLAIN);
			
			//  HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin",
			//  bin).addPart("comment", comment).build();
			  
		//	  httppost.setEntity(reqEntity);
			 
			System.out.println("executing request " + httppost.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println("Response content length: " + resEntity.getContentLength());
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	private static void downFile() {
        try {

            String path = "E:\\downurl\\2016022302\\";

            File downFileUrl = new File(path);
            File[] files = downFileUrl.listFiles();
            for (File file:files) {
                BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String downParas = null;
                while((downParas=bfr.readLine())!=null){
                    System.out.println("下载参数:"+downParas);
                    String[] dows = downParas.split("&");
                    if(dows==null||dows.length<3){
                        System.out.println("数据不正常downParas:"+downParas);
                    }else{
                        String tenderFlod = path+dows[0].trim();
                        File tender_fold = new File(tenderFlod.trim());

                        if(!tender_fold.exists()){
                            System.out.println("创建文件夹:"+tenderFlod.trim());
                            tender_fold.mkdir();
                        }
                        String leiFold = tenderFlod+"\\"+dows[1].trim();
                        File lei_Fold = new File(leiFold);
                        if(!lei_Fold.exists()){
                            System.out.println("创建文件夹:"+leiFold);
                            lei_Fold.mkdir();
                        }
                    //    HttpClient httpclient = new DefaultHttpClient();
                        CloseableHttpClient httpclient =HttpClientBuilder.create().build();
                        HttpPost httppost = new HttpPost("http://imagelocal.eloancn.com/xxxdownImg.action");
						/*
						 * StringBody fileName = new StringBody(dows[2]); MultipartEntity reqEntity =
						 * new MultipartEntity(); reqEntity.addPart("imgPath", fileName);//fileName文件名称
						 * httppost.setEntity(reqEntity);
						 */
                        CloseableHttpResponse response = httpclient.execute(httppost);
                        int statusCode = response.getStatusLine().getStatusCode();
                        if(statusCode == HttpStatus.SC_OK){
                            System.out.println("服务器正常响应....."+dows[2].substring(dows[2].lastIndexOf("/")+1)+"下载完成。");
                            HttpEntity resEntity = response.getEntity();
                            String savepath = lei_Fold+"//"+dows[2].substring(dows[2].lastIndexOf("/")+1).trim();
                            FileOutputStream fos = new FileOutputStream(new File(savepath));
                            resEntity.writeTo(fos);
                        }
                    }



                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	public Map<String, Object> doPostTest(String url, String bucketres) {
		 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		String responseEntityToString = null;
 
		// 创建Post请求
		//HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerTwo");
		HttpPost httpPost = new HttpPost(url);
 
		StringEntity entity = new StringEntity(bucketres, "UTF-8");
 
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
 
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
 
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				responseEntityToString=EntityUtils.toString(responseEntity); 
				System.out.println("响应内容为:" + responseEntityToString);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Map<String, Object> mapRemote= JSON.parseObject(responseEntityToString.toString(), Map.class);
		return mapRemote;
	}
	/**
	 * post 请求带参数
	 * @throws Exception
	 */
	public void HttpClientPost() throws Exception {
		// 获取默认的请求客户端
		CloseableHttpClient client = HttpClients.createDefault();
		// 通过HttpPost来发送post请求
		HttpPost httpPost = new HttpPost("http://www.itcast.cn");
		/*
		 * post带参数开始
		 */
		// 第三步:构造list集合,往里面丢数据
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("username", "zhangsan");
		BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password", "123456");
		list.add(basicNameValuePair);
		list.add(basicNameValuePair2);
		// 第二步:我们发现Entity是一个接口,所以只能找实现类,发现实现类又需要一个集合,集合的泛型是NameValuePair类型
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
		// 第一步:通过setEntity 将我们的entity对象传递过去
		httpPost.setEntity(formEntity);
		/*
		 * post带参数结束
		 */
		// HttpEntity
		// 是一个中间的桥梁,在httpClient里面,是连接我们的请求与响应的一个中间桥梁,所有的请求参数都是通过HttpEntity携带过去的
		// 通过client来执行请求,获取一个响应结果
		CloseableHttpResponse response = client.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String str = EntityUtils.toString(entity, "UTF-8");
		System.out.println(str);
		// 关闭
		response.close();
	}

	
	
	/**
     * 带参数的post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public  void doPost(String url, Map<String, Object> map) throws Exception {
    	   CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    	// 声明httpPost请求
         HttpPost httpPost = new HttpPost(url);
 
        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();
 
            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
 
            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
            formEntity.setContentType("Content-Type:application/json");
 
            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }
 
        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);
 
        // 解析response封装返回对象httpResult
       // HttpTinyClient.HttpResult httpResult = null;
        if (response.getEntity() != null) {
           // httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8");
        } else {
          //  httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回结果
       
    }


	
	/**
	 * 
	 * @author liunn
	 * @param post 上传图片
	 */
	public  void uploadImagePost(String url) throws ClientProtocolException, IOException{
	    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	    CloseableHttpResponse httpResponse = null;
	//    StringBuffer buffer = null;
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
	 //   HttpPost httpPost = new HttpPost("http://localhost:8080/storage/post/{bucket}/{path}");
	    HttpPost httpPost = new HttpPost(url);
	    httpPost.setConfig(requestConfig);
	    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	    //multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
	         
	    //File file = new File("F:\\Ken\\1.PNG");
	    //FileBody bin = new FileBody(file); 
	         
	    File file1 = new File("E:/图像/juan_/juan_backup1.jpg");
	    File file2 = new File("E:/图像/juan_/juan_backup2.jpg");
	    File file3 = new File("E:/图像/juan_/juan_backup3.jpg");
	    //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
	    //当设置了setSocketTimeout参数后,以下代码上传PDF不能成功,将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
	    //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
	    multipartEntityBuilder.addBinaryBody("file",file1);
	   multipartEntityBuilder.addBinaryBody("file",file2);
	    multipartEntityBuilder.addBinaryBody("file",file3);
	    //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
	    multipartEntityBuilder.addTextBody("comment", "this is comment");
	//    multipartEntityBuilder.addTextBody("qxid", "liunnaijuanjuan");
	 //   multipartEntityBuilder.addTextBody("imgCounts", "3");
	    
	    HttpEntity httpEntity = multipartEntityBuilder.build();
	    
	    
	  Map<String, Object> map=new HashMap<String, Object>();
	  map.put("qxid", "liunnaijuanjuan");
	  map.put("imgCounts", "3");
	 /**   String jsonString = JSON.toJSONString(map); 
		StringEntity entity = new StringEntity(jsonString, "UTF-8");
		httpPost.setEntity(entity);
	*/
	    
	    List<NameValuePair> params = new ArrayList<NameValuePair>();
	    // 遍历map,设置参数到list中
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }

        // 创建form表单对象
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf-8");
        formEntity.setContentType("Content-Type:application/json");
	    
	    httpPost.setEntity(formEntity);
	    	
	    
	    httpPost.setEntity(httpEntity);
	    httpResponse = httpClient.execute(httpPost);
	     System.out.println(url);
	  	  System.out.println("--------------------------------------------------------------------");
	    HttpEntity responseEntity = httpResponse.getEntity();
	    int statusCode= httpResponse.getStatusLine().getStatusCode();
	    if(statusCode == 200){
	        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
	        StringBuffer buffer  = new StringBuffer();
	        String str = "";
	        while(StringUtils.isNotEmpty(str = reader.readLine())) {
	            buffer.append(str);
	            
	        }
	        System.out.println("接受到的图片服务器上的数据 是:------------------");
	        System.out.println(buffer.toString());
	   
	    }
	         
	    httpClient.close();
	    if(httpResponse!=null){
	        httpResponse.close();
	    }
	     
	}
	
	
	
	
	  public void ssl() throws java.security.cert.CertificateException {
	  CloseableHttpClient httpclient = null; 
	  try { 
	  	KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
	  	FileInputStream instream =new FileInputStream(new File("d:\\tomcat.keystore")); 
	  try { // 加载keyStore d:\\tomcat.keystore 
	  trustStore.load(instream, "123456".toCharArray()); }
	  finally { try { 
		  instream.close(); 
		  } catch (Exception ignore) { 
			  
		  } } 
	  //相信自己的CA和所有自签名的证书
	  SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore,
	  new TrustSelfSignedStrategy()).build(); 
	  // 只允许使用TLSv1协议
	  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" }, null,
	  SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); 
	  httpclient= HttpClients.custom().setSSLSocketFactory(sslsf).build(); 
	  // 创建http请求(get方式)
	  HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action");
	  System.out.println("executing request" + httpget.getRequestLine());
	  
	  CloseableHttpResponse response = httpclient.execute(httpget); try {
	  HttpEntity entity = response.getEntity();

	  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(); } } catch
	  (ParseException e) { e.printStackTrace(); } catch (IOException e) {
	  e.printStackTrace(); 
	  } catch (KeyManagementException e) {
	  e.printStackTrace(); 
	  } catch (NoSuchAlgorithmException e) {
	  e.printStackTrace(); 
	  } catch (KeyStoreException e) { 
		  e.printStackTrace(); }
	  finally { if (httpclient != null) { 
		  try { httpclient.close(); } catch
	  (IOException e) { 
			  e.printStackTrace(); 
			  } } } }
	  
	
	
}

有两点需要说明:1这个是我使用的,所以其中参数没动,如做使用,需要修改。2有些方法抄袭了别人的代码,如做提醒,发我消息,我会添加上参考地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值