关于java的http请求的工具类

直接粘贴复制,各种请求参数都支持,需要什么的请求方式就调用不同的方法,想你所想,写你所写

package net.bx.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class HTTPutil {
	 private static final String DEFAULT_CHARSET = "UTF-8";
	 /**
	     * 发送Get请求
	     * @param url
	     * @return
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws IOException 
	     * @throws KeyManagementException 
	     */
	    private static String getHeaderParam(String url, Map<String, String> headerParam) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
	        StringBuffer bufferRes = null;
	        TrustManager[] tm = { new MyX509TrustManager() };  
	        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
	        sslContext.init(null, tm, new java.security.SecureRandom());  
	        // 从上述SSLContext对象中得到SSLSocketFactory对象  
	        SSLSocketFactory ssf = sslContext.getSocketFactory();
	        
	        URL urlGet = new URL(url);
	        HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();

            if(headerParam!=null){

                for (String key : headerParam.keySet()) {
                    http.addRequestProperty(key,headerParam.get(key));
                }
            }
	        // 连接超时
	        http.setConnectTimeout(25000);
	        // 读取超时 --服务器响应比较慢,增大时间
	        http.setReadTimeout(25000);
	        http.setRequestMethod("GET");
	        http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	        http.setSSLSocketFactory(ssf);
	        http.setDoOutput(true);
	        http.setDoInput(true);
	        http.connect();
	        
	        InputStream in = http.getInputStream();
	        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
	        String valueString = null;
	        bufferRes = new StringBuffer();
	        while ((valueString = read.readLine()) != null){
	            bufferRes.append(valueString);
	        }
	        in.close();
	        if (http != null) {
	            // 关闭连接
	            http.disconnect();
	        }
	        return bufferRes.toString();
	    }
	    
	    /**
	     * 发送Get请求
	     * @param url
	     * @return
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws IOException 
	     * @throws KeyManagementException 
	     */
	    public static String get(String url,Boolean https,Map<String,String> headerParam) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
	     if(https != null && https){
	    	 return getHeaderParam(url, headerParam);
	     }else{
	    	 	StringBuffer bufferRes = null;
	            URL urlGet = new URL(url);
	            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
             //请求头信息
             if(headerParam!=null){

                 for (String key : headerParam.keySet()) {
                     http.addRequestProperty(key,headerParam.get(key));
                 }
             }
	            // 连接超时
	            http.setConnectTimeout(25000);
	            // 读取超时 --服务器响应比较慢,增大时间
	            http.setReadTimeout(25000);
	            http.setRequestMethod("GET");
	            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	            http.setDoOutput(true);
	            http.setDoInput(true);
	            http.connect();
	            
	            InputStream in = http.getInputStream();
	            BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
	            String valueString = null;
	            bufferRes = new StringBuffer();
	            while ((valueString = read.readLine()) != null){
	                bufferRes.append(valueString);
	            }
	            in.close();
	            if (http != null) {
	                // 关闭连接
	                http.disconnect();
	            }
	            return bufferRes.toString();
	     }
	    }
	    
	    /**
	     *  发送Get请求
	     * @param url
	     * @param params
	     * @return
	     * @throws IOException 
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws KeyManagementException 
	     */
	    public static String get(String url, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
	        return getHeaderParam(initParams(url, params), null);
	    }
	    /**
	     *  发送Post请求
	     * @param url
	     * @param params
	     * @return
	     * @throws IOException 
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws KeyManagementException 
	     */
	    private static String post(String url, String params,Map<String,String> headerParam,String method) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	    	StringBuffer bufferRes = null;
	        TrustManager[] tm = { new MyX509TrustManager() };
	        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
	        sslContext.init(null, tm, new java.security.SecureRandom());
	        // 从上述SSLContext对象中得到SSLSocketFactory对象  
	        SSLSocketFactory ssf = sslContext.getSocketFactory();
	        URL urlGet = new URL(url);
	        HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();

            if(headerParam!=null){

                for (String key : headerParam.keySet()) {
                    http.addRequestProperty(key,headerParam.get(key));
                }
            }
	        // 连接超时
	        http.setConnectTimeout(25000);
	        // 读取超时 --服务器响应比较慢,增大时间
	        http.setReadTimeout(25000);
	        http.setRequestMethod(method);
	        http.setRequestProperty("Content-Type","application/json");
	        http.setSSLSocketFactory(ssf);
	        http.setDoOutput(true);
	        http.setDoInput(true);
	        http.connect();
	        OutputStream out = http.getOutputStream();
	        out.write(params.getBytes("UTF-8"));
	        out.flush();
	        out.close();
	        InputStream in = http.getInputStream();
	        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
	        String valueString = null;
	        bufferRes = new StringBuffer();
	        while ((valueString = read.readLine()) != null){
	            bufferRes.append(valueString);
	        }
	        in.close();
	        if (http != null) {
	            // 关闭连接
	            http.disconnect();
	        }
	        return bufferRes.toString();
	    }

    public static String post(String url, String params,Boolean https,Map<String,String> headerParam) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        return post(url,params,https,headerParam,"POST");
    }
	    
	    /**
	     *  发送Post请求
	     * @param url
	     * @param params
	     * @return
	     * @throws IOException 
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws KeyManagementException 
	     */
	    public static String post(String url, String params,Boolean https,Map<String,String> headerParam,String method) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	    	 if(https != null && https){
	 	    	 return post(url,params,headerParam,method);
	 	     }else{
	 	    	StringBuffer bufferRes = null;
		        URL urlPost = new URL(url);
		        HttpURLConnection http = (HttpURLConnection) urlPost.openConnection();
		        //请求头信息
				if(headerParam!=null){

                    for (String key : headerParam.keySet()) {
                        http.addRequestProperty(key,headerParam.get(key));
                    }
				}
		        // 连接超时
		        http.setConnectTimeout(25000);
		        // 读取超时 --服务器响应比较慢,增大时间
		        http.setReadTimeout(25000);
                http.setRequestMethod(method);
		        http.setRequestProperty("Content-Type","application/json");
		        http.setDoOutput(true);
		        http.setDoInput(true);
		        http.connect();
		        OutputStream out = http.getOutputStream();
		        out.write(params.getBytes("UTF-8"));
		        out.flush();
		        out.close();
                 InputStream in = http.getInputStream();
		        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		        String valueString = null;
		        bufferRes = new StringBuffer();
		        while ((valueString = read.readLine()) != null){
		            bufferRes.append(valueString);
		        }
		        in.close();
		        if (http != null) {
		            // 关闭连接
		            http.disconnect();
		        }
		        return bufferRes.toString();
	 	     }
	    	
	    }
	    
	    /**
	     * 构造url
	     * @param url
	     * @param params
	     * @return
	     */
	    private static String initParams(String url, Map<String, String> params){
	        if (null == params || params.isEmpty()) {
	            return url;
	        }
	        StringBuilder sb = new StringBuilder(url);
	        if (url.indexOf("?") == -1) {
	            sb.append("?");
	        } else {
	            sb.append("&");
	        }
	        boolean first = true;
	        for (Entry<String, String> entry : params.entrySet()) {
	            if (first) {
	                first = false;
	            } else {
	                sb.append("&");
	            }
	            String key = entry.getKey();
	            String value = entry.getValue();
	            sb.append(key).append("=");
	            if (StringUtils.isNotEmpty(value)) {
	                try {
	                    sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
	                } catch (UnsupportedEncodingException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return sb.toString();
	    }
	    
	    /**
	     * 发送Get请求
	     * @param url
	     * @return
	     * @throws NoSuchProviderException 
	     * @throws NoSuchAlgorithmException 
	     * @throws IOException 
	     * @throws KeyManagementException 
	     */
	    public static Map<String,String> getHeaders(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
	    	 	Map<String,String> headers = new HashMap<String,String>();
	            URL urlGet = new URL(url);
	            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
	            // 连接超时
	            http.setConnectTimeout(25000);
	            // 读取超时 --服务器响应比较慢,增大时间
	            http.setReadTimeout(25000);
	            http.setRequestMethod("GET");
	            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	            http.setDoOutput(true);
	            http.setDoInput(true);
	            http.connect();
	            
	            headers.put("contentType",http.getContentType());
	            if (http != null) {
	                // 关闭连接
	                http.disconnect();
	            }
	            return headers;
	    }

	/**
	 *  发送Post请求
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		if(https != null && https){
			return post(url,params);
		}else{
			StringBuffer bufferRes = null;
			URL urlPost = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlPost.openConnection();
			// 连接超时
			http.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢,增大时间
			http.setReadTimeout(25000);
			http.setRequestMethod("POST");
			http.setRequestProperty("Content-Type","application/json");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			OutputStream out = http.getOutputStream();
			out.write(params.getBytes("UTF-8"));
			out.flush();
			out.close();
			InputStream in = http.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null){
				bufferRes.append(valueString);
			}
			in.close();
			if (http != null) {
				// 关闭连接
				http.disconnect();
			}
			return bufferRes.toString();
		}

	}

	/**
	 *  发送Post请求
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		StringBuffer bufferRes = null;
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL urlGet = new URL(url);
		HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
		// 连接超时
		http.setConnectTimeout(25000);
		// 读取超时 --服务器响应比较慢,增大时间
		http.setReadTimeout(25000);
		http.setRequestMethod("POST");
		http.setRequestProperty("Content-Type","application/json");
		http.setRequestProperty("Accept","application/json");
		http.setRequestProperty("Authorization","WECHATPAY2-SHA256-RSA2048"+" "+params);

		http.setSSLSocketFactory(ssf);
		http.setDoOutput(true);
		http.setDoInput(true);
		http.connect();
		OutputStream out = http.getOutputStream();
		out.write(params.getBytes("UTF-8"));
		out.flush();
		out.close();
		InputStream in = http.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		String valueString = null;
		bufferRes = new StringBuffer();
		while ((valueString = read.readLine()) != null){
			bufferRes.append(valueString);
		}
		in.close();
		if (http != null) {
			// 关闭连接
			http.disconnect();
		}
		return bufferRes.toString();
	}


	/**
	 * 发送Get请求
	 * @param url
	 * @return
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws KeyManagementException
	 */
	private static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
		StringBuffer bufferRes = null;
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL urlGet = new URL(url);
		HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
		// 连接超时
		http.setConnectTimeout(25000);
		// 读取超时 --服务器响应比较慢,增大时间
		http.setReadTimeout(25000);
		http.setRequestMethod("GET");
		http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		http.setSSLSocketFactory(ssf);
		http.setDoOutput(true);
		http.setDoInput(true);
		http.connect();

		InputStream in = http.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		String valueString = null;
		bufferRes = new StringBuffer();
		while ((valueString = read.readLine()) != null){
			bufferRes.append(valueString);
		}
		in.close();
		if (http != null) {
			// 关闭连接
			http.disconnect();
		}
		return bufferRes.toString();
	}

	/**
	 * 发送Get请求
	 * @param url
	 * @return
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws KeyManagementException
	 */
	public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
		if(https != null && https){
			return get(url);
		}else{
			StringBuffer bufferRes = null;
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			// 连接超时
			http.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢,增大时间
			http.setReadTimeout(25000);
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();

			InputStream in = http.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null){
				bufferRes.append(valueString);
			}
			in.close();
			if (http != null) {
				// 关闭连接
				http.disconnect();
			}
			return bufferRes.toString();
		}
	}


	public static String postUrlJson(String url, String params) throws Exception {

		Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

        HttpClient client = new HttpClient();
        HttpMethod post = new PostMethod(url + "?" + params);
        try {
            client.executeMethod(post);
            byte[] responseBody = post.getResponseBody();
            String result = new String(responseBody,"UTF-8");
            return result;
        } finally {
            post.releaseConnection();
        }

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值