HttpClient总结

HttpClient主要作用:

1、读取网页(Http,Https)内容

2、使用post方式提交数据

public String sendMessage(String mobile, String content, String ext, String stime, String rrid, String msgfmt) {
	//创建HttpClientBuilder  
	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
	String result = null;
	try {
	    System.out.println(content);
	    String tempCont = URLEncoder.encode(content, "gb2312");
	    HttpGet httpGet = new HttpGet(requestUrl + "?sn=" + sn + "&pwd=" + pwd + "&mobile=" + mobile + "&content=" + tempCont + "&ext=" + ext);
	    //执行get请求  
	    HttpResponse httpResponse;
	    httpResponse = closeableHttpClient.execute(httpGet);
	    //获取响应消息实体  
	    HttpEntity entity = httpResponse.getEntity();
	    result = EntityUtils.toString(entity, "UTF-8");
	} catch (Exception e) {
	    e.printStackTrace();
	} finally {
	    try {
		//关闭流并释放资源  
		closeableHttpClient.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return result;
} 

先对CloseableHttpClient有个概念,日后总结。。。

public int pushMessage(String did, String message, String sessionIdstr, String postUrl) {
	int result = 0;
	//创建HttpClientBuilder  
	HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	CloseableHttpClient httpclient = httpClientBuilder.build();
	HttpPost httppost = new HttpPost(postUrl.toString());
	List<NameValuePair> formparams = new ArrayList<NameValuePair>();
	formparams.add(new BasicNameValuePair("did", did));
	formparams.add(new BasicNameValuePair("message", message));
	formparams.add(new BasicNameValuePair("sessionId", sessionIdstr));
	UrlEncodedFormEntity uefEntity;
	try {
	    uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
	    httppost.setEntity(uefEntity);
	    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();//设置请求和传输超时时间
	    httppost.setConfig(requestConfig);
	    CloseableHttpResponse response = httpclient.execute(httppost);
	    try {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    String resData = EntityUtils.toString(entity, "UTF-8");
		    JSONObject resultJson = JSONObject.fromObject(resData);
		    if (resultJson.optInt("recode") == 1) {
			result = 1;
		    }
		}
	    } finally {
		response.close();
	    }
	} catch (ClientProtocolException e) {
	    e.printStackTrace();
	} catch (UnsupportedEncodingException e1) {
	    e1.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	} finally {
	    // 关闭连接,释放资源    
	    try {
		httpclient.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return result;
}

参考: HttpClient学习总结

猜你喜欢

转载自blog.csdn.net/chang_li/article/details/71353229