java http get post请求 https请求实现

直接贴代码

 


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpUtil {
	
	public static String httpPost(String url,Map<String, String> parametes){
		String str = "";
		HttpClient httpClient = new HttpClient();
		PostMethod psotMethod = new PostMethod(url);
		if(parametes!=null&&parametes.size()>0){
			Set<String> keys = parametes.keySet();
			for(String key:keys){
				psotMethod.setParameter(key, parametes.get(key));//这里添加参数
			}
		}
		psotMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");//请求编码
		psotMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		try {
			//执行getMethod
			int statusCode =  httpClient.executeMethod(psotMethod); 
			/*if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "+ psotMethod.getStatusLine());
			}*/
			//读取内容 
			byte[] responseBody = psotMethod.getResponseBody();
			str  = new String(responseBody,"utf-8");
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  finally {
			//释放连接
			psotMethod.releaseConnection();
		}
		return str;
	}
	
	public static String httpGet(String url){
		//System.out.println(url);
		String str = "";
		//构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		//创建GET方法的实例
		GetMethod getMethod = new GetMethod(url);
		//使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		new DefaultHttpMethodRetryHandler());
		try {
			//执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
				+ getMethod.getStatusLine());
			}
			//读取内容 
			byte[] responseBody = getMethod.getResponseBody();
			//处理内容
			str = new String(responseBody,"utf-8");
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  finally {
			//释放连接
			getMethod.releaseConnection();
		}
		return str;
	}
	public static StringBuffer httpsSendGet(String path) 
    {  
	    StringBuffer sb = new StringBuffer(); 
       // String path = "https://kyfw.12306.cn/otn/lcxxcx/query?purpose_codes=ADULT&queryDate=2015-05-22&from_station=BJP&to_station=ZZF";  
        TrustManager[] trustAllCerts = new TrustManager[]{ 
        		new X509TrustManager() { 
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
                        return null; 
                    } 
                    public void checkClientTrusted( 
                        java.security.cert.X509Certificate[] certs, String authType) { 
                    } 
                    public void checkServerTrusted( 
                        java.security.cert.X509Certificate[] certs, String authType) { 
                    } 
                } 	            }; 
       try { 
                SSLContext sc = SSLContext.getInstance("SSL"); 
                sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
            } catch (Exception e) { 
            } 
       try { 
            URL url = new URL(path); 
            HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); 
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); 
            String line; 
            while ((line = rd.readLine()) != null) { 
            	//sb.append(line);
            	sb.append(line);
            } 
           	rd.close(); 
            } catch (MalformedURLException e) { 
            } catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            return sb;
    }
}

jar包地址

http://download.csdn.net/detail/huidanyige/8603109

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值