http-POST/GET 实现方式,附源代码

package com.example.edibase.service

import org.apache.http.HttpResponse
import org.apache.http.NameValuePair
import org.apache.http.client.config.RequestConfig
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.client.methods.HttpRequestBase
import org.apache.http.client.utils.URLEncodedUtils
import org.apache.http.entity.StringEntity
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.springframework.stereotype.Service

@Service
class HttpPost45Service {

    static int TIMEOUT = 60 // 超时时间,秒
    /**
     * post请求for XML
     * @param url
     * @param body
     * @param params
     * @param headersMap
     * @return
     */
     String httpPost45xml(String url, String body) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String str="";
        try {
//        HttpGet httpGet = new HttpGet(url)
            HttpPost post = new HttpPost(url);
            //httpClient 4.5版本的超时参数配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(60000).setConnectionRequestTimeout(60000)
                    .setSocketTimeout(60000).build();
            post.setConfig(requestConfig);
            //往BODY里填充数据主体
            StringEntity entitys = new StringEntity(body, "utf-8");
            entitys.setContentEncoding("UTF-8");
            entitys.setContentType("application/xml");
            post.setEntity(entitys);
            HttpResponse response = httpclient.execute(post);
//        System.out.println("得到的结果:" + response.getStatusLine())//得到请求结果
            str = EntityUtils.toString(response.getEntity());//得到请求回来的数据
            return str;
        } catch (Exception e) {
            // System.out.println("发送 POST 请求出现异常!" + e);
            str = "<response><flag>failure</flag><code>480</code><message>" + e.toString() + "</message></response>";
            e.printStackTrace();
            // log.error("远程服务未开启", e);
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return str;
    }
    /**
     * POST 请求for json
     * @param url
     * @param jsonParam
     * @return
     */
     String httpPost45Json(String url, String jsonParam) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String str;
        try {
//url?后面的即为post parmas 参数,bodu 放在数据流中进行传输

//        HttpGet httpGet = new HttpGet(url)
            HttpPost post = new HttpPost(url);
            //httpClient 4.5版本的超时参数配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(60000).setConnectionRequestTimeout(60000)
                    .setSocketTimeout(60000).build();
            post.setConfig(requestConfig);
            //往BODY里填充数据主体
            StringEntity entitys = new StringEntity(jsonParam, "utf-8");
            entitys.setContentEncoding("UTF-8");
            entitys.setContentType("application/json");
            post.setEntity(entitys);
            HttpResponse response = httpclient.execute(post);
//        System.out.println("得到的结果:" + response.getStatusLine())//得到请求结果
            str = EntityUtils.toString(response.getEntity());//得到请求回来的数据
            return str;
        } catch (Exception e) {
            // System.out.println("发送 POST 请求出现异常!" + e);
            str = "{\"flag\":\"failure\",\"code\":\"480\",\"message\":" + e.toString() + "}";
            e.printStackTrace();
            // log.error("远程服务未开启", e);
        } finally {
            try {
                if (httpclient != null) {
                    httpclient.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return str;
    }

    /**
     * request请求方法 支持POST和GET在方法中传参
     * @param url
     * @param method  请求方式
     * @param body  body报文信息
     * @param params 参数信息
     * @param headersMap 头信息
     * @param charsetName
     * @return
     */
    static String httpRequest(String url, String method, String body, Map<String, String> params, Map<String, String> headersMap = null, String charsetName = ‘utf-8‘) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 请求参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>()
            params?.each {
                nvps.add(new BasicNameValuePair(it.key, it.value?.toString()))
            }
            HttpRequestBase request = null
            if (‘GET‘.equalsIgnoreCase(method)) {
                String paramStr = URLEncodedUtils.format(nvps, charsetName)
                request = new HttpGet(url + ‘?‘ + paramStr)
            } else if (‘POST‘.equalsIgnoreCase(method)) {
                String paramStr = URLEncodedUtils.format(nvps, charsetName)
                request = new HttpPost(url + ‘?‘ + paramStr)
//                request.setEntity(new UrlEncodedFormEntity(nvps, charsetName))
                StringEntity entitys = new StringEntity(body, "utf-8");
                request.setEntity(entitys)
            } else {
                return null
            }
            // 请求头信息
            headersMap?.each {
                request.addHeader(it.key, it.value?.toString())
            }
            // 超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(1 * TIMEOUT * 1000).setConnectionRequestTimeout(1 * TIMEOUT * 1000)
                    .setSocketTimeout(1 * TIMEOUT * 1000).build();
            request.setConfig(requestConfig);
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(request);
            try {
                // 获取响应实体
                final org.apache.http.HttpEntity entity = response.getEntity()
                // 打印响应状态
                System.out.println("--------------------------------------" + response.getStatusLine())
                if (entity != null) {
                    String resp = EntityUtils.toString(entity, charsetName)
                    EntityUtils.consume(entity)
                    return resp
                }
                return null
            } finally {
                response.close();
            }
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

调用方法

package com.example.edibase.controller

import com.alibaba.fastjson.JSONArray
import com.example.edibase.config.domain.ApiMessage
import com.example.edibase.domain.ResponseMessage
import com.example.edibase.domain.XmlResponseMessage
import com.example.edibase.endpoint.tools.Xml2JsonService
import com.example.edibase.service.EdiService
import com.example.edibase.service.HttpPost45Service
import com.example.edibase.service.HttpPostService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@RestController
@RequestMapping("/api/edi/edibase2")
class EdiBase2Controller extends EdiService {

    protected String getCharsetName() {
        return "UTF-8"
    }

    @Autowired
    HttpPost45Service hp45Svc
    @Autowired
    HttpPostService hpSvc
    @Autowired
    Xml2JsonService xtjSvc


    @RequestMapping(value = "in", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    ResponseMessage inbound(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) {
        ResponseMessage rsp = ResponseMessage.success();
        rsp.data = ApiMessage.MSG_INTF_0001
        return rsp;
    }

    @RequestMapping(value = "test", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    ResponseMessage test(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) {
        ResponseMessage rsp = ResponseMessage.success();
        String body = readBody(request)
        Map<String, String> qmParams = this.getFinalParams()
        qmParams.putAll(["method": "singleitem_synchronize", "customerId": "123", "body": body])
        Map<String,String> headersMap=["Accept":"application/json","Content-Type":"application/json"]
//        String result = hpSvc.sendPost_body_json("http://localhost:9020/api/edi/edibase2/in", body)
        String result = hp45Svc.httpRequest("http://localhost:9020/api/edi/edibase2/in", "POST", body, qmParams,headersMap)
        println result

        rsp = JSONArray.parseObject(result, ResponseMessage.class)
//        rsp = convertToObject(result, ResponseMessage.class,"json")
//        rsp.data=ApiMessage.MSG_INTF_0001
        return rsp;
    }

    @RequestMapping(value = "inxml", method = RequestMethod.POST, produces = "text/xml")
    ResponseMessage inxml(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) {
        ResponseMessage rsp = ResponseMessage.success();
        String body = readBody(request)
        println body
        rsp.data = ApiMessage.MSG_INTF_0001
        return rsp;
    }

    @RequestMapping(value = "testxml", method = RequestMethod.POST, produces = "application/xml")
    XmlResponseMessage testxml(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) {

        String body = readBody(request)
        Map<String, String> qmParams = this.getFinalParams()
        qmParams.putAll(["method": "singleitem_synchronize", "customerId": "123", "body": body])
        Map<String,String> headersMap=["Accept":"application/xml","Content-Type":"application/xml"]
//        String result = hpSvc.httpPost45xml("http://127.0.0.1:9002/api/edi/qimen/in", body, qmParams, null)
//        String result = hpSvc.sendPost_body_xml("http://127.0.0.1:9002/api/edi/qimen/in?method=singleitem_synchronize&format=xml&customerId=123", body)
        String result = hp45Svc.httpRequest("http://127.0.0.1:9002/api/edi/qimen/in", "POST", body, qmParams)
        println result
        String jsonS = xtjSvc.xml2Json(result)
//        rsp = JSONArray.parseObject(result, ResponseMessage.class)
        def rsp = convertToObject(jsonS, ResponseMessage.class, "json")
//        rsp.data=ApiMessage.MSG_INTF_0001
        return XmlResponseMessage.fromResponseMessage(rsp)
    }


    @RequestMapping(value = "insql", method = RequestMethod.POST, produces = "application/xml")
    ResponseMessage insql(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, String> params) {
        ResponseMessage rsp = ResponseMessage.success();
        String body = readBody(request)
        println body
        rsp.data = ApiMessage.MSG_INTF_0001
        return rsp;
    }

    /**
     * 从request中读取body
     * @param request
     * @return
     */
    String readBody(HttpServletRequest request) {
        StringBuilder sb
        BufferedReader br

        br = new BufferedReader(new InputStreamReader(request.getInputStream(), charsetName))
        sb = new StringBuilder()
        char[] tempchars = new char[30] // 使用readLine会有回车换行的问题
        int charread
        try {
            while ((charread = br.read(tempchars)) != -1) {
                if (charread != tempchars.length) {
                    sb.append(String.valueOf(tempchars, 0, charread))
                } else {
                    sb.append(tempchars)
                }
            }
        } catch (Throwable t) {
            t.printStackTrace()
            sb.setLength(0)
        } finally {
            br.close()
        }
        sb.toString()
    }

    /**
     * 基础url参数
     * @return
     */
    Map<String, String> getFinalParams() {
        return ["timestamp"  : DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()),
                "format"     : ‘json‘,
                "v"          : ‘1.0‘,
                "sign_method": ‘md5‘]
    }
}

http-POST/GET 实现方式,附源代码

上一篇:Html:行级元素和块级元素标签列表


下一篇:本地Ajax模拟后台数据的问题,控制台报错信息