httpclientUtils

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
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.util.EntityUtils;

public class HttpclientUtils {
	
	
	public  static String  doGet(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpPost = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Content-Type", "application/json");
		String result="";
		try {
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
	
	
	public  static String  doGet(String url,Map<String,String> param) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String result="";
		try {
			URIBuilder builder = new URIBuilder(url);
		        for(String key: param.keySet()){
		            builder.setParameter(key, param.get(key));
		        }
		
		HttpGet httpGet = new HttpGet(builder.build());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpGet.setConfig(requestConfig);
		HttpResponse response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		result = EntityUtils.toString(entity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}

	public static String  doPostForJson(String url, String jsonParams) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
		HttpResponse response=null;
		 String result="";
		try {
			 response = httpClient.execute(httpPost);
			  result = EntityUtils.toString(response.getEntity());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
	
	

	
	public static void doPostForJson(String url,String ip ,int port, String jsonParams,String username,String password) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(new AuthScope(ip, port),
					new UsernamePasswordCredentials(username, password));
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Content-Type", "application/json");
		try {
			httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
			System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
			HttpResponse response = httpClient.execute(httpPost,context);
			System.out.println(" code:" + response.getStatusLine().getStatusCode());
			System.out.println("doPostForInfobipUnsub response" + response.getStatusLine().toString());
			System.out.println(String.valueOf(response.getStatusLine().getStatusCode()));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("post failure :caused by-->" + e.getMessage().toString()); 
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public  static String  doPut(String url,String jsonParams) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(url);
		
		
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPut.setConfig(requestConfig);
		httpPut.setHeader("Content-Type", "application/json");
		String result="";
		try {
			httpPut.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
	public  static String  doDelete(String url) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpDelete httpDel = new HttpDelete(url);
		
		
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpDel.setConfig(requestConfig);
		String result="";
		try {
			HttpResponse response = httpClient.execute(httpDel);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
	public  static String  doPut(String url) throws URISyntaxException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPut httpPut = new HttpPut(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPut.setConfig(requestConfig);
		httpPut.setHeader("Content-Type", "application/json");
		String result="";
		try {
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity,"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}
	
	public static Map<String,String> upload(String url) throws ClientProtocolException, IOException{
	    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
	    CloseableHttpResponse httpResponse = null;
	    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
	    HttpPost httpPost = new HttpPost(url);
	    httpPost.setConfig(requestConfig);
	    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
	    File file = new File(new File("").getCanonicalPath()+File.separator+"upload.jpg");
	    
	    multipartEntityBuilder.addBinaryBody("fileName",file);
	    HttpEntity httpEntity = multipartEntityBuilder.build();
	    httpPost.setEntity(httpEntity);
	         
	    httpResponse = httpClient.execute(httpPost);
	    HttpEntity responseEntity = httpResponse.getEntity();
	    int statusCode= httpResponse.getStatusLine().getStatusCode();
	    String result = EntityUtils.toString(responseEntity,"UTF-8");
	    httpClient.close();
	    if(httpResponse!=null){
	        httpResponse.close();
	    }
	    HashMap<String, String> resultMap = new HashMap<String,String>();
	    resultMap.put("statusCode", String.valueOf(statusCode));
	    resultMap.put("result", result);
	     return resultMap;
	}
	
}

  

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

 

posted on 2018-07-16 21:01  知了不了了之  阅读(532)  评论(0编辑  收藏  举报