JAVA利用HttpClient进行POST请求(HTTPS)
final HttpClientUtil httpClientUtil = new HttpClientUtil(); final Map<String, String> map = Maps.newHashMap(); map.put("username", workNo); map.put("password", passwd); final String resultStr = httpClientUtil.doPost(url, map, CHARSET);
/*
* 利用HttpClient进行post请求的工具类
*/
/* * 利用HttpClient进行post请求的工具类 */ public class HttpClientUtil { public String doPost(String url,Map<String,String> map,String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ httpClient = new SSLClient(); httpPost = new HttpPost(url); //设置参数 final List<NameValuePair> list = new ArrayList<>(); final Iterator iterator = map.entrySet().iterator(); while(iterator.hasNext()){ final Entry<String,String> elem = (Entry<String, String>) iterator.next(); list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); } if(!list.isEmpty()){ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if(response != null){ final HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } }catch(Exception ex){ ex.printStackTrace(); } return result; } /** * 发送get请求 * @param url 链接地址 * @param charset 字符编码,若为null则默认utf-8 * @return */ public String doGet(String url,String charset){ if(null == charset){ charset = "utf-8"; } HttpClient httpClient = null; HttpGet httpGet= null; String result = null; try { httpClient = new SSLClient(); httpGet = new HttpGet(url); final HttpResponse response = httpClient.execute(httpGet); if(response != null){ final HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } } catch (Exception e) { e.printStackTrace(); } return result; } }