http接口工具类
2015-11-16 16:29
519 查看
package com.in.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HTTP工具类 * * @author lixiangyang * */ public class HttpUtils { private static Logger logger = Logger.getLogger(HttpUtils.class); public static final String UTF8 = "UTF-8"; // 定义编码格式 UTF-8 public static final String GBK = "GBK"; // 定义编码格式 GBK private static final String EMPTY = ""; /** * HttpClient连接SSL url: https://localhost:8443/myDemo/Ajax/serivceJ.action * password : "123456".toCharArray() */ public static String ssl(String url, String password) { String sslContent = EMPTY; CloseableHttpClient httpclient = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("/tomcat.keystore")); try { // 加载keyStore d:\\tomcat.keystore trustStore.load(instream, password.toCharArray()); } catch (CertificateException e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } // 相信自己的CA和所有自签名的证书 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) .build(); // 只允许使用TLSv1协议 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); // 创建http请求(get方式) HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { sslContent = EntityUtils.toString(entity); EntityUtils.consume(entity); } } finally { response.close(); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } return sslContent; } /** * post方式提交表单(模拟用户登录请求) * url:http://localhost:8080/myDemo/Ajax/serivceJ.action * encodeCharset:"UTF-8" formparams:form表单数据 */ public static String postForm(String url, List<NameValuePair> formparams, String encodeCharset) { logger.info("postForm"); String postFormContent = EMPTY; // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost(url); // 创建参数队列 // formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("username", "admin")); // formparams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, encodeCharset); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (null != entity) { postFormContent = EntityUtils.toString(entity, encodeCharset); } } 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 postFormContent; } // 重载,增加cookie选项 public static String postForm(String url, List<NameValuePair> formparams, String username, String encodeCharset) { logger.info("postForm"); String postFormContent = EMPTY; // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost(url); httppost.setHeader("Cookie", "username=" + username); // 创建参数队列 // formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("username", "admin")); // formparams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, encodeCharset); httppost.setEntity(uefEntity); System.out.println("executing request " + httppost.getURI()); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (null != entity) { postFormContent = EntityUtils.toString(entity, encodeCharset); } } 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 postFormContent; } /** * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 * url:"http://182.254.218.140:8080/in_user/user_query" * encodeCharset:"UTF-8" */ public static String post(String url, List<NameValuePair> formparams, String encodeCharset) { String postContent = EMPTY; // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost(url); // 创建参数队列 // formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("type", "house")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, encodeCharset); httppost.setEntity(uefEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { postContent = EntityUtils.toString(entity, encodeCharset); } } 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 postContent; } public static String post(String userName, String url, List<NameValuePair> formparams, String encodeCharset) { String postContent = EMPTY; // 创建默认的httpClient实例. CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httppost HttpPost httppost = new HttpPost(url); httppost.setHeader("Cookie", "username=" + userName); // 创建参数队列 // formparams = new ArrayList<NameValuePair>(); // formparams.add(new BasicNameValuePair("type", "house")); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, encodeCharset); httppost.setEntity(uefEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { postContent = EntityUtils.toString(entity, encodeCharset); } } 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 postContent; } /** * 发送 get请求 url:http://182.254.218.140:8080/in_user/user_query * username=bobby password=123456xyzp */ public static String get(String userName, String url) { String getContent = EMPTY; CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 创建HttpGet HttpGet httpget = new HttpGet(url); httpget.setHeader("Cookie", "username=" + userName); // 执行get请求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 获取响应实体 HttpEntity entity = response.getEntity(); if (entity != null) { getContent = EntityUtils.toString(entity);// 响应内容 } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return getContent; } /** * 套餐类型账户查询 * * @param userName * @param type * 账户类型 * @param url * @return */ public static String get(String userName, String type, String url) { String getContent = EMPTY; CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 创建HttpGet HttpGet httpget = new HttpGet(url); httpget.setHeader("Cookie", "username=" + userName); // 执行get请求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 获取响应实体 HttpEntity entity = response.getEntity(); if (entity != null) { getContent = EntityUtils.toString(entity);// 响应内容 } } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return getContent; } /** * 发送用户关怀信息 * * @param userName * @param type * @param tplId * @param subject * @param dataOne * @param dataTwo */ public static void sendCareMsg(final String userName, final String type, final String tplId, final String subject, final String dataOne, final String dataTwo, final String dataThree) { logger.info("调用in_message/send_care_msg用户关怀发送消息."); logger.info("userName=" + userName + "; type=" + type + "; tplId=" + tplId + "; subject=" + subject + "; dataOne=" + dataOne + "; dataTwo=" + dataTwo + "; dataThree=" + dataThree); new Thread(new Runnable() { @Override public void run() { try { String inMessageIp = Util.modelIps.get("in_message") == null ? "" : Util.modelIps.get("in_message").get(0); if (userName != null && !"".equals(userName) && inMessageIp != null && !"".equals(inMessageIp)) { String uri = "http://" + inMessageIp + "/in_message/send_care_msg"; String cookie = "username=service@ininin.com"; Map<String, String> params = new HashMap<String, String>(); params.put("username", userName); params.put("type", type); params.put("tpl_id", tplId); params.put("subject", subject); if (dataOne != null) { params.put("data_one", dataOne); } if (dataTwo != null) { params.put("data_two", dataTwo); } if (dataThree != null) { params.put("data_three", dataThree); } String resultJson = doPost(uri, cookie, params); logger.info("发送消息. " + resultJson); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * post请求数据 * * @param uri * url * @param cookie * cookie * @param params * 参数 * @return */ public static String doPost(String uri, String cookie, Map<String, String> params) { String resultJson = null; if (uri == null || "".equals(uri)) { return resultJson; } CloseableHttpClient httpclient = HttpClients.createDefault();// 创建默认的httpClient实例. try { HttpPost httppost = new HttpPost(uri);// 创建httppost if (cookie != null && !"".equals(cookie)) { httppost.setHeader("Cookie", cookie); } if (params != null && !params.isEmpty()) { List<NameValuePair> formparams = new ArrayList<NameValuePair>();// 创建参数队列 String key = null; for (Iterator<String> ite = params.keySet().iterator(); ite.hasNext();) { key = ite.next(); formparams.add(new BasicNameValuePair(key, params.get(key))); } UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(uefEntity); } CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { resultJson = EntityUtils.toString(entity, "UTF-8"); } } finally { response.close(); // ... httppost.abort(); } } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close();// 关闭连接,释放资源 } catch (IOException e) { e.printStackTrace(); } } return resultJson; } /** * 上传文件 */ /* * public void upload() { CloseableHttpClient httpclient = * HttpClients.createDefault(); try { HttpPost httppost = new * HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action"); * * FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg")); * StringBody comment = new StringBody("A binary file of some kind", * ContentType.TEXT_PLAIN); * * HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", * bin).addPart("comment", comment).build(); * * httppost.setEntity(reqEntity); * * System.out.println("executing request " + httppost.getRequestLine()); * CloseableHttpResponse response = httpclient.execute(httppost); try { * System.out.println("----------------------------------------"); * System.out.println(response.getStatusLine()); HttpEntity resEntity = * response.getEntity(); if (resEntity != null) { System.out.println( * "Response content length: " + resEntity.getContentLength()); } * EntityUtils.consume(resEntity); } finally { response.close(); } } catch * (ClientProtocolException e) { e.printStackTrace(); } catch (IOException * e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch * (IOException e) { e.printStackTrace(); } } * * } */ }
相关文章推荐
- OpenWrt搭建uhttpd+php+sqlite的环境
- 网络资源>>资源站点
- 移动端网络优化
- 6.请求网络步骤
- 移动APP后端网络处理一些问题记录
- IPhone设备信息获取与网络状态监测
- 自己动手写网络爬虫
- 【转】TCP协议中的三次握手和四次挥手(图解)
- 网络流
- 轻松把玩HttpClient之配置ssl,采用设置信任自签名证书实现https
- 不同框架实现的WebService的服务端获取HttpServletRequest的方法
- Heritrix3.3.0源码阅读 URI过滤规则
- BAT解密:互联网技术发展之路(7)- 网络层技术剖析
- HTTPURLConnection中接收数据流
- [Android_机制]_Http和Socket连接区别
- [TCPIP] 传输控制协议 Note
- [TCPIP] 传输控制协议 Note
- [TCPIP] DNS Note
- Http与Socket
- [TCPIP] DNS Note