HttpClent请求示例 Post Get

一.Post请求

1.post请求http接口

public static String httpPost(String url,Map<String,String> param_map,String encoding) throws ClientProtocolException, 
	IOException {
		String result="";
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
        		.setConnectTimeout(10000)
        		.setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .setRedirectsEnabled(true)
                .build();
		//创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//创建httppost对象
		HttpPost httppost = new HttpPost(url);
		//设置超时时间
		httppost.setConfig(requestConfig);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if(param_map != null){
			for(Entry<String,String> entry : param_map.entrySet()){
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		//设置请求参数到httppost对象中
		httppost.setEntity(new UrlEncodedFormEntity(nvps,encoding));
		//设置Header信息
		httppost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
		httppost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
               //我这边需要接收json格式数据,设置这个报文头,根据实际情况可以不添加
		httppost.addHeader("Accept", "application/json");
		//执行请求,获取返回结果
		CloseableHttpResponse httpresp = client.execute(httppost);
		HttpEntity httpentity = httpresp.getEntity();
		if(httpentity!=null){
			result = EntityUtils.toString(httpentity, encoding);
		}
		//关闭entity流
		EntityUtils.consume(httpentity);
		//释放链接
		httpresp.close();
		return result;
	}

2.post请求https接口

采用绕过安全协议的策略,创建sslclient类:

public class SSLClient extends DefaultHttpClient{
	
	public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

post请求方法:

public static String httpsPost(String url,Map<String, String> params){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,HTTP.UTF_8);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
        	httpPost.releaseConnection();
        }
        return result;
	}   

二.Get请求

get请求http接口:

public static String httpGet(String url,Map<String,String> param_map,String encoding) throws ClientProtocolException, 
	IOException {
		String result="";
		//拼接请求参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if(param_map != null){
			for(Entry<String,String> entry : param_map.entrySet()){
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		String param = EntityUtils.toString(new UrlEncodedFormEntity(nvps,encoding));
		url = url+"?"+param;
        //配置超时时间
        RequestConfig requestConfig = RequestConfig.custom()
        		.setConnectTimeout(10000)
        		.setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .setRedirectsEnabled(true)
                .build();
		//创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		//创建httpget对象
        HttpGet httpget = new HttpGet(url);
        //设置超时时间
        httpget.setConfig(requestConfig);
		//设置Header信息
		httpget.setHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
		httpget.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		//执行请求,获取返回结果
		CloseableHttpResponse httpresp = client.execute(httpget);
		HttpEntity httpentity = httpresp.getEntity();
		if(httpentity!=null){
			result = EntityUtils.toString(httpentity, encoding);
		}
		//关闭entity流
		EntityUtils.consume(httpentity);
		//释放链接
		httpresp.close();
		return result;
	}

3.测试示例

以https post请求为例,其它类似:

	public static void main(String[] args) {
		String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
		Map<String,String> param_map = new HashMap<String, String>();
		param_map.put("tel", "15012345678");
	    String result = httpsPost(url,param_map);
		System.out.println(result);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值