java http请求接口

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

	private HttpClientUtil() {
	}

	/**
	 * get请求
	 * @param url
	 * @param params
	 * @param headers 授权等headers
	 * @return
	 */
	public static String doGet(String url, Map<String, String> params, Map<String, String> headers) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (params != null) {
				for (String key : params.keySet()) {
					builder.addParameter(key, params.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			//设置请求Header
			if (headers != null) {
				for (String key : headers.keySet()) {
					httpGet.setHeader(key, headers.get(key));
				}
			}
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * get请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doGet(String url, Map<String, String> params) {
		return doGet(url, params,null);
	}
	
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		return doGet(url, null,null);
	}

	/**
	 * get方式获取文件流
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 */
	public static byte[] getFile(String url, Map<String,String> params, Map<String, String> headers){
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpEntity result = null;
		byte[] data = null;
		CloseableHttpResponse response = null;

		try{
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (params != null) {
				for (String key : params.keySet()) {
					builder.addParameter(key, params.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			//设置请求Header
			if (headers != null) {
				for (String key : headers.keySet()) {
					httpGet.setHeader(key, headers.get(key));
				}
			}

			//发送请求
			response = httpClient.execute(httpGet);

			//判断响应状态
			if(response.getStatusLine().getStatusCode() == 200){
				result = response.getEntity();
				data = EntityUtils.toByteArray(result);
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return data;
	}

	public static byte[] getFile(String url, Map<String,String> params){
		return getFile(url, params,null);
	}

	/**
	 * post formdata
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map<String, Object> params) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			HttpPost httpPost=null;
			// 创建参数列表
			if (params != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				StringBuilder paramstr=new StringBuilder("");
				for (String key:params.keySet()){
					paramstr.append(key + "=" + URLEncoder.encode((String) params.get(key), "UTF-8") + "&");
				}
				// 创建Http Post请求
				httpPost = new HttpPost(url+"?"+paramstr);

				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
			}

			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}
	
	/**
	 * POST请求
	 *
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 */
	public static String doPost(String url, Map<String, String> params, Map<String, String> headers) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			//组装请求头
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
			if (headers != null && !headers.isEmpty()) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpPost.setHeader(entry.getKey(), entry.getValue());
				}
			}

			//组装请求体
			List<NameValuePair> paramList = new ArrayList<>();
			if (params != null && !params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
			httpPost.setEntity(requestEntity);

			//发送请求
			response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			String result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);

			response.close();
			httpClient.close();
			return result;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					System.out.println("response close failed");
				}
			}
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					System.out.println("httpClient close failed");
				}
			}
		}
		return null;
	}

	/**
	 * POST请求
	 * @param url
	 * @param params formdata
	 * @param headers header
	 * @return
	 */
	public static String doPost(String url, Map<String, String> params, Map<String, String> headers) {
		//配置,发送https请求时,忽略ssl证书认证(否则会报错没有证书)
		SSLContext sslContext = null;
		try {
			sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
				@Override
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			}).build();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslContext).
			setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			//设置请求Header
			if (headers != null && !headers.isEmpty()) {
				for (String key : headers.keySet()) {
					httpPost.setHeader(key, headers.get(key));
				}
			}
			// 创建请求内容
			// 创建参数列表
			if (params != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : params.keySet()) {
					paramList.add(new BasicNameValuePair(key, params.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}
	
	public static String doPost(String url) {
		return doPost(url, null);
	}

	/**
	 * post 请求发送json
	 * @param url
	 * @param param
	 * @param token_header
	 * @return
	 * @throws Exception
	 */
	public static String doPostJson(String url, Map<String, Object> param, String token_header) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			httpPost.setHeader("HTTP Method","POST");
			httpPost.setHeader("Connection","Keep-Alive");
			httpPost.setHeader("Content-Type","application/json;charset=utf-8");
			if(token_header != null) {
				httpPost.setHeader("x-authentication-token", token_header);
			}
			StringEntity entity = new StringEntity(JSON.toJSONString(param));
			entity.setContentType("application/json;charset=utf-8");
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if(response!=null){
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}

	/**
	 * httpClient 发送文件
	 * @param param 其他参数
	 * @param is 文件流
	 * @param fileName 文件名
	 * @return
	 * @throws Exception
	 */
	public static String doUpload(String uploadURL, Map<String, Object> param, InputStream is, String fileName) throws Exception {
		String result ="";
		try {
			//创建HttpClient
			HttpPost httpPost  = new HttpPost(uploadURL);
			httpPost.setHeader("ContentType","text/xml");
			HttpPost post = new HttpPost(uploadURL);
			HttpEntity entity = new FileEntity(new File(fileName));
			post.setEntity(entity);
			CloseableHttpClient httpClient = HttpClients.createDefault();
			CloseableHttpResponse response = httpClient.execute(post);
			System.out.println(response.getStatusLine().getStatusCode());
			//执行提交
			HttpEntity responseEntity = response.getEntity();
			if(responseEntity != null){
				//将响应的内容转换成字符串
				result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
			}

			response.close();
			httpClient.close();
		}catch (Exception ex){
			ex.printStackTrace();
		}finally {
			try {
				if(is!=null){
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
}

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值