博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
http请求
阅读量:6720 次
发布时间:2019-06-25

本文共 14086 字,大约阅读时间需要 46 分钟。

package com.j1.mai.util;import java.io.IOException;import java.util.Map;import java.util.Set;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.NameValuePair;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import org.apache.log4j.Logger;public class HttpUtils {    /**     * 发送HTTP请求     *     * @param url     * @param propsMap 发送的参数     */    public static HttpResponse httpPost(String url, Map
propsMap) { HttpResponse response = new HttpResponse(); String responseMsg = ""; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 if (propsMap != null) { // 参数设置 Set
keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key) .toString()); } postMethod.addParameters(postData); } postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); try { int statusCode = httpClient.executeMethod(postMethod);// 发送请求 response.setStatusCode(statusCode); if (statusCode == HttpStatus.SC_OK) { // 读取内容 byte[] responseBody = postMethod.getResponseBody(); // 处理返回的内容 responseMsg = new String(responseBody, "utf-8"); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 关闭连接 } response.setContent(responseMsg); return response; } /** * 发送HTTP请求 * * @param url */ public static HttpResponse httpGet(String url) { HttpResponse response = new HttpResponse(); String responseMsg = ""; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { int statusCode = httpClient.executeMethod(getMethod);// 发送请求 response.setStatusCode(statusCode); if (statusCode == HttpStatus.SC_OK) { // 读取内容 byte[] responseBody = getMethod.getResponseBody(); // 处理返回的内容 responseMsg = new String(responseBody, "utf-8"); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { getMethod.releaseConnection();// 关闭连接 } response.setContent(responseMsg); return response; } /** * 发送HTTP--GET请求 * * @param url * @param propsMap * 发送的参数 */ public static String httpGetSend(String url) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url);// GET请求 try { // http超时5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); // 设置 get 请求超时为 5 秒 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); httpClient.executeMethod(getMethod);// 发送请求 // 读取内容 byte[] responseBody = getMethod.getResponseBody(); // 处理返回的内容 responseMsg = new String(responseBody, "utf-8"); } catch (Exception e) { Logger.getLogger(HttpUtils.class).error(e.getMessage()); e.printStackTrace(); } finally { getMethod.releaseConnection();// 关闭连接 } return responseMsg; } /** * 发送HTTP请求 * * @param url * @param propsMap * 发送的参数 */ public static String httpSend(String url, Map
propsMap) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 // postMethod. // 参数设置 Set
keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key) .toString()); } postMethod.addParameters(postData); try { httpClient.executeMethod(postMethod);// 发送请求// Log.info(postMethod.getStatusCode()); // 读取内容 byte[] responseBody = postMethod.getResponseBody(); // 处理返回的内容 responseMsg = new String(responseBody); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 关闭连接 } return responseMsg; } /** * 发送Post HTTP请求 * * @param url * @param propsMap * 发送的参数 * @throws IOException * @throws HttpException */ public static PostMethod httpSendPost(String url, Map
propsMap,String authrition) throws Exception { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 postMethod.addRequestHeader("Authorization",authrition); postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置 Set
keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key) .toString()); } postMethod.addParameters(postData); httpClient.executeMethod(postMethod);// 发送请求 return postMethod; } /** * 发送Post HTTP请求 * * @param url * @param propsMap * 发送的参数 * @throws IOException * @throws HttpException */ public static PostMethod httpSendPost(String url, Map
propsMap) throws Exception { String responseMsg = ""; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置 Set
keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key) .toString()); } postMethod.addParameters(postData); httpClient.executeMethod(postMethod);// 发送请求 return postMethod; } /** * 发送Get HTTP请求 * * @param url * @param propsMap * 发送的参数 * @throws IOException * @throws HttpException */ public static GetMethod httpSendGet(String url, Map
propsMap) throws Exception { String responseMsg = ""; HttpClient httpClient = new HttpClient(); GetMethod getMethod = new GetMethod(url);// GET请求 getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); // 参数设置 Set
keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { getMethod.getParams().setParameter(key, propsMap.get(key) .toString()); } httpClient.executeMethod(getMethod);// 发送请求 return getMethod; } }
/**     * 发送http请求     *      * @param url     * @param empName     * @param loginPassWd     * @return     */    public String httpSend(String url, Member member) {        StringBuffer buffer = new StringBuffer();        String responseContent = null;        try {            URL url_new = new URL(url);// 创建连接            HttpURLConnection connection = (HttpURLConnection) url_new                    .openConnection();            connection.setDoOutput(true);            connection.setDoInput(true);            connection.setRequestMethod("POST");            connection.setUseCaches(false);            connection.setInstanceFollowRedirects(true);            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式            connection.connect();            connection.connect();            // POST请求            DataOutputStream out = new DataOutputStream(                    connection.getOutputStream()); // utf-8编码 ;            String sign = null;            String time = DateUtils.longToDateAll(System.currentTimeMillis());            String token = "91A1643059824847938125BA0AC0F557"; // token 不产于传送            String format = "json"; // 传送方式            String method = "saveMember";// 调用方法            String sessionKey = "123456789078945";// sessionkey            String up_date = time;// 上传日期 yyyy-mm-dd            String version = "1.0.2";// 版本号            try {                sign = Md5Util.Bit32(format + method + sessionKey + token                        + up_date + version);            } catch (Exception e1) {                e1.printStackTrace();            }            JSONObject obj = new JSONObject();            obj.element("sessionKey", sessionKey);            obj.element("method", method);            obj.element("format", format);            obj.element("up_Date", time);            obj.element("sign", sign);            obj.element("version", version);            JSONObject objbusinessdate = new JSONObject();                        objbusinessdate.element("memCardNo", member.getMemberId()+"-j1");// memberId                                objbusinessdate.element("idCardCode", member.getIdentifyCard());// 身份证            // 存入数据优先设置realName,如果realName为空,就设置loginName;                                    if (member.getRealName() != null|| member.getRealName() != "") {                                objbusinessdate.element("contactor", member.getRealName());// 姓名            }else{                    objbusinessdate.element("contactor", member.getLoginName());// 姓名                }            //性别            objbusinessdate.element("sex", member.getSex());                        //身份证                String identifyCard=member.getIdentifyCard();                if(identifyCard.length()>0){               String subBirthday=    identifyCard.substring(6, 14);                String subBirth=subBirthday.substring(0, 4)+"-"+subBirthday.substring(4, 6)+"-"+subBirthday.substring(6, 8);                objbusinessdate.element("birthDay",subBirth);// 生日            }            objbusinessdate.element("address", member.getAddress());// 地址            objbusinessdate.element("mTel", member.getMobile());// 移动电话            objbusinessdate.element("eMail", member.getEmail());// email            //如果没有拿到值,为避免接口报错,进行默认值的设置                    if(member.getEmpId()==null||member.getEmpId()=="" ){                objbusinessdate.element("roptrId", "50048");// 操作人            }else{                objbusinessdate.element("roptrId", member.getEmpId());// 操作人            }            if(member.getDeptId()==null|| member.getDeptId()==""){                objbusinessdate.element("enrDeptId", "1015");// 操作门店名称            }else{                objbusinessdate.element("enrDeptId", member.getDeptId());// 操作门店名称            }            objbusinessdate.element("ybCardCode", member.getHospitalCard());// 医保卡            objbusinessdate.element("regTime", member.getRegTime());// 注册时间            objbusinessdate.element("note", member.getNotes()); // 备注            obj.element("businessData", objbusinessdate);            System.out.println(obj.toString());            out.writeBytes(obj.toString());            out.flush();            // 读取响应            int length = (int) connection.getContentLength();// 获取长度            System.out.println("length:" + length);            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {                System.out.println("网络错误异常!!!!");            }            InputStream in = connection.getInputStream();            BufferedReader rds = new BufferedReader(new InputStreamReader(in,                    "UTF-8"));            String tempLine = rds.readLine();            StringBuffer tempStr = new StringBuffer();            if (tempLine != null) {                tempStr.append(tempLine);                tempLine = rds.readLine();            }            responseContent = tempStr.toString();            out.close();            rds.close();            connection.disconnect();            System.out.println("  Buffer============= " + buffer.toString());            return responseContent;        } catch (IOException e) {            e.printStackTrace();        }        return responseContent;    }
/**     *      * 验证loginToken的有效性     *      * @param loginToken 必填     * @return     * @throws Exception      */    public Map checkTokenUUId(String uid, String loginToken) throws Exception{                String prikey = PropertyConfigurer.getString("yiqianbaourl");        String url = prikey + "/logintoken/verify/"+uid+"?loginToken="+loginToken;        //验证 loginToken的有效性        Map
propsMap = new HashMap
(); GetMethod postMethod = HttpUtils.httpSendGet(url, propsMap); //验证loginToken的有效性 成功状态200 if(postMethod.getStatusCode()==StringMsg.SUC_STATES){ String obj = responseGetString(postMethod); Map map = (Map) JSONObject.toBean(JSONObject.fromObject(obj),Map.class); if(!map.containsKey("legal")){
//若验证成功 LOG.error("**********loginToken验证失败,令牌超时*********"); } return map; } return null; }

 

转载地址:http://ascmo.baihongyu.com/

你可能感兴趣的文章
Java集合--TreeSet
查看>>
BurpSuite系列----Extender模块(扩展器)
查看>>
CSS media queries
查看>>
session的序列化、钝化、活化
查看>>
PHP中的抽象类与抽象方法/静态属性和静态方法/PHP中的单利模式(单态模式)/串行化与反串行化(序列化与反序列化)/约束类型/魔术方法小结...
查看>>
==与===的区别
查看>>
JS 在指定数组中随机取出N个不重复的数据
查看>>
软件开发模型
查看>>
Windows Store App下代码加载page resource和resw文件里的string
查看>>
数据结构基本知识点总结
查看>>
【翻译】前景img-sprites, 高对比模式分析
查看>>
进程和线程的一个简单形象的解释
查看>>
The road to learning English-Grammar
查看>>
Python多线程编程之多线程加锁
查看>>
shell报错:-bash: [: ==: 期待一元表达式 解决方法 ([: ==: unary operator expected)
查看>>
opengl 杂记
查看>>
兼容MIUI5和MIUI6的开启悬浮窗设置界面
查看>>
基于FPGA的DDS设计(一)
查看>>
.net 开发框架(一)[数据通用层]
查看>>
sql-ISNULL函数(转载)
查看>>