精华内容
下载资源
问答
  • JAVA使用http请求,实现webservice接口数据调用 前言 第一次接触webservice的调用,在经过了这个过程之后,不得不说,比较麻烦。总结一下网上的各种方案 1、直接AXIS调用远程的web service 2、直接SOAP调用远程的...

    JAVA使用http请求,实现webservice接口数据调用

    前言

    第一次接触webservice的调用,在经过了这个过程之后,不得不说,比较麻烦。总结一下网上的各种方案
    1、直接AXIS调用远程的web service
    2、直接SOAP调用远程的webservice
    3、生成客户端调用方式
    4、HTTP请求方式
    由于对HTTP笔记熟悉一点,因此才用了http求情的方式。下面详细介绍一下整个使用的过程。

    springboot项目调用webservice接口。

    其实和springboot一点关系都没有。由于初次接触,直接采用最原生的方式完成整个功能,活不多说,放上代码。

    第一,发送http请求(URL,请求参数xml)
        //发送post请求
        private String sendHttpPost(String url, String body) throws Exception {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //String header = InterfaceEnCode.getInterfaceKey();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "text/xml");
            //httpPost.setHeader("access-token", header);
            httpPost.setEntity(new StringEntity(body, "UTF-8"));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // System.out.println(response.getStatusLine().getStatusCode() + "\n");
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            // System.out.println(responseContent);
            response.close();
            httpClient.close();
            return responseContent;
        }
    
    第二,根据接口定义封装请求参数
     	/**
         * xml请求体封装
         */
        private String getXmlRquest(String timestamp, String soaoXmlBody, String webName) {
            String soaoXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice\">\n" +
                    "   <soapenv:Body>\n" +
                    "      <web:" + webName + ">\n" +
                    "         <requestInfo>\n" +
                    "            <requestHeader>\n" +
                    "               <appid>" + APPID + "</appid>\n" +
                    "               <timestamp>" + date.getTime() + "</timestamp>\n" +
                    "               <sign>" + getXmlhSign(timestamp, soaoXmlBody) + "</sign>\n" +
                    "            </requestHeader>\n" +
                    "            <requestBody>\n" + soaoXmlBody + "\n" +
                    "            </requestBody>\n" +
                    "         </requestInfo>\n" +
                    "      </web:" + webName + ">\n" +
                    "   </soapenv:Body>\n" +
                    "</soapenv:Envelope>\n";
    
            return soaoXML;
        }
    
    第三,xml格式化(很多时候,xml在传输过程中会出现转义)
        //xml格式化,消除转义字符
        private static String formatXml(String inputXML) throws Exception {
            String xml = null;
            SAXReader reader = new SAXReader();
            XMLWriter writer = null;
            Document document = reader.read(new StringReader(inputXML));
            try {
                if (document != null) {
                    StringWriter stringWriter = new StringWriter();
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    //format.setNewLineAfterDeclaration(false);
                    writer = new XMLWriter(stringWriter, format);
                    writer.setEscapeText(false);
                    writer.write(document);
                    writer.flush();
                    xml = stringWriter.getBuffer().toString();
                }
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return xml;
        }
    
    

    -writer.setEscapeText(false); 取消xml转义(格式化操作)。

    第四,xml解析,将返回的xml进行解析(此处采用dom4j)
      /**
         * 获取主数据节点
         *
         * @param doc
         * @return
         */
        private Iterator getMasterDataByTimestamp(Document doc, String webName) {
            // System.out.println(webName);
            Element rootElt = doc.getRootElement(); // 获取根节点
            Element body = rootElt.element("Body");//获取子节点body
    
            Element info = body.element(webName + "Response");//获取子节点ns2对应的接口内容
    
            Element returnIfo = info.element("return");//获取子节点return
    
            Element responseInfo = returnIfo.element("responseInfo");//获取子节点responseInfo
    
            Element responseBody = responseInfo.element("responseBody");//获取子节点responseBody
    
            Element mdmDataList = responseBody.element("mdmDataList");//获取子节点mdmDataList
    
            Iterator mdmData = mdmDataList.elementIterator("mdmData");//获取子节点mdmData
            return mdmData;
        }
    
    

    -注意,在进行xml解析是,要根据自己的xml格式,一级一级获取节点,最终拿取到自己想要的数据。如果不想采用此方式,可以采取其它方式解析返回的xml字符串。

    第五,签名加密(如果xml不存在签名验证,则不需要此步骤)
      /**
         * xmlhSign获取
         *
         * @param timestamp
         * @param requestBody
         * @return
         */
        private String getXmlhSign(String timestamp, String requestBody) {
            //APPID+&+参数 XML 字符串+&+TIMESTAMP+&+SIGNKEY
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(APPID);
            stringBuffer.append("&");
            stringBuffer.append(requestBody);
            stringBuffer.append("&");
            stringBuffer.append(timestamp);
            stringBuffer.append("&");
            stringBuffer.append(SIGNKEY);
            //原始码:
            System.out.println("原始码:");
            System.out.println(stringBuffer.toString());
            //MD5加密
            String encode = MD5Utils.MD5Encode(stringBuffer.toString(), "");
            System.out.println("Sign:" + encode);
            return encode;
        }
    
    

    – String encode = MD5Utils.MD5Encode(stringBuffer.toString(), “”);这一个采用了一个MD5加密的工具类

    第六,最终的整合,发送请求,解析参数
     public List<HisStaff> getWardStaffInfo() {
            String timestamp = String.valueOf(date.getTime());
            String url = "http://localhost:8080/csc/rs";
            String webName = "getMasterData";
            List<HisStaff> list = new ArrayList<HisStaff>();
            try {
                //添加body参数内容,Code 为私有变量,已经在类里面定义好了
                String soaoXmlBody = "<mdmCode>" + Code + "</mdmCode><timestamp>1</timestamp>";
                //封装请求体
                String xmlRquest = getXmlRquest(timestamp, soaoXmlBody, webName);
                //System.out.println("soaoXML:" + xmlRquest);
    
                //获取请求结果
                String formatXml = this.sendHttpPost(url, xmlRquest);
                //xml格式
                String result = formatXml(formatXml);
                //解析xml
                doc = DocumentHelper.parseText(result); // 将字符串转为doc对象
                //System.out.println(result);
                Iterator iterator = getMasterDataByTimestamp(doc, webName); //此处返回的是一个Iterator 对象,如果当前节点内部是一个list集合列表,可采用此方法,遍历获取集合内部的节点
                //封装返回结果
                while (iterator.hasNext()) {
                    HisStaff hisStaff = new HisStaff();
                    //遍历集合获取数据
                    Element itemEle = (Element) iterator.next();
                    hisStaff.setStaffId(itemEle.elementTextTrim("staffId")); 
                    hisStaff.setWardArea(itemEle.elementTextTrim("wardId")); 
                    hisStaff.setExt1(itemEle.elementTextTrim("isDelete")); 
                    list.add(hisStaff);
                }
                return list;
            } catch (
                    Exception e) {
                e.printStackTrace();
            }
            return list;
        }
    

    总结:代码涉及到的http请求发送,xml格式化,xml解析,MD5加密。由于xml疯转和解析过程比较复杂,可能需要一点耐心,不能再格式上有错误。否则请求发送会失败。

    –如果有什么问题,欢迎留言

    展开全文
  • 使用java发送Http请求

    2019-08-27 14:47:01
    使用java发送Http请求 使用jdk自带HttpUrlRequest发送请求,简单化,轻量化,不集成第三方的框架,不会引入第三方的包,适用于简单场景的第三方远程交互。 发送GET请求 GET请求是最简单的请求,所需要的参数直接...

    使用java发送Http请求

    使用jdk自带HttpUrlRequest发送请求,简单化,轻量化,不集成第三方的框架,不会引入第三方的包,适用于简单场景的第三方远程交互。
    

    发送GET请求

    GET请求是最简单的请求,所需要的参数直接拼接到请求URL后面就可以,后端服务器收到请求后就可以解析并处理。
    
       /**
         * 发送get请求
         * @return 返回请求结果
         */
        public String doGet() {
            if(params != null && !params.isEmpty()) {
                url += "?";
                url += createParams();
            }
            URL u ;
            HttpURLConnection connection ;
            try {
                u = new URL(url);
                log.error(url);
                connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(connectTimeout);
                connection.setReadTimeout(readTimeout);
                connection.setRequestProperty("Content-Type",contentType);
                if(heads != null){
                    for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                        connection.setRequestProperty(stringStringEntry.getKey(),stringStringEntry.getValue());
                    }
                }
                InputStream is = connection.getInputStream();
                return getResponse(is);
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            } catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
    
        private String createParams() {
            if(params != null && !params.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, String> stringObjectEntry : params.entrySet()) {
                    try {
                        sb.append(stringObjectEntry.getKey()).append("=").append(URLEncoder.encode(stringObjectEntry.getValue(),"UTF-8")).append("&");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                sb.delete(sb.length() - 1, sb.length());
                return sb.toString();
            }
            return "";
        }
    

    发送POST请求

    POST请求分几种情况,根据Content-Type的类型,如下:
    
    • application/json 将请求体使用json格式化为字符串,在请求体里面封闭传输
    • application/x-www-form-urlencoded 使用表单提交,将value使用url编码之后,封装成 key=value的格式在请求体里面传输
    • multipart/form-data 将参数使用boundary分隔,在服务端解析,可以传输文件

    application/json格式请求

    /**
         * 发送post请求
         * @return 请求结果
         */
        public String doPost() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                connection = getPostConnection();
                out = connection.getOutputStream();
                if(params != null && !params.isEmpty()) {
                    out.write(toJSONString(params).getBytes());
                }
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
    

    实际请求的报文如下:

    POST /files/lists HTTP/1.1
    Host: localhost:8080
    Content-Type: application/json
    User-Agent: PostmanRuntime/7.15.2
    Accept: */*
    Cache-Control: no-cache
    Postman-Token: 49cb9315-21f2-44ab-875e-33cfabe58112,fc03e72f-8364-46b5-a81a-c0ee217228f1
    Host: localhost:8080
    Accept-Encoding: gzip, deflate
    Content-Length: 32
    Connection: keep-alive
    cache-control: no-cache
    
    {
      "size": 1,
      "start": 1
    }
    

    application/x-www-form-urlencoded格式请求

    /**
         * 发送post表单请求
         * @return 请求结果
         */
        public String doPostFormUrl() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                this.contentType = "application/x-www-form-urlencoded; charset=UTF-8";
                this.contentType = "multipart/form-data";
                connection = getPostConnection();
                out = connection.getOutputStream();
                if(params != null && !params.isEmpty()) {
                    out.write(createParams().getBytes());
                }
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
    

    实际请求报文如下:

    POST /test/formTest HTTP/1.1
    Host: localhost:8080
    Content-Type: application/x-www-form-urlencoded
    User-Agent: PostmanRuntime/7.15.2
    Accept: */*
    Cache-Control: no-cache
    Postman-Token: dcbeee5f-b7f5-45a4-860c-7393514471f5,afdc6811-7655-45ce-8989-cba62c3b434d
    Host: localhost:8080
    Accept-Encoding: gzip, deflate
    Content-Length: 166
    Connection: keep-alive
    cache-control: no-cache
    
    cname=1&bucketName=22222222222222222222
    

    multipart/form-data格式请求

     /**
         * 发送post表单请求
         * @return 请求结果
         */
        public String doPostFormData() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                this.contentType = "multipart/form-data; boundary=" + BOUNDARY_STRING;
                connection = getPostConnection();
                out = connection.getOutputStream();
                StringBuilder sb = new StringBuilder();
                if(params != null && !params.isEmpty()) {
                    for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
                        sb.append(BOUNDARY);
                        sb.append("Content-Disposition:form-data;name=\"");
                        sb.append(stringStringEntry.getKey());
                        sb.append("\"\r\n\r\n");
                        sb.append(stringStringEntry.getValue());
                        sb.append("\r\n");
                    }
                    out.write(sb.toString().getBytes());
                }
                if(file != null && fileName != null) {
                    StringBuilder sf = new StringBuilder();
                    sf.append(BOUNDARY);
                    sf.append("Content-Disposition:form-data;name=\"");
                    sf.append(fileName)
                    .append("\"; filename=\"")
                    .append(file)
                    .append("\"\r\n\r\n");
                    out.write(sf.toString().getBytes());
                    File f = new File(file);
                    InputStream is = new FileInputStream(f);
                    byte[] buffer = new byte[8192];
                    int count = 0;
                    while ((count = is.read(buffer)) != -1) {
                        out.write(buffer, 0, count);
                    }
                    out.write("\r\n\r\n".getBytes());
                    is.close();
                }
                out.write(("--" + BOUNDARY_STRING + "--\r\n").getBytes());
                log.error(sb.toString());
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
    

    实际发送的请求报文如下:

    POST /test/formTest HTTP/1.1
    Host: localhost:8080
    Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
    User-Agent: PostmanRuntime/7.15.2
    Accept: */*
    Cache-Control: no-cache
    Postman-Token: dcbeee5f-b7f5-45a4-860c-7393514471f5,ad334d00-9477-4eba-a122-cf14be29df11
    Host: localhost:8080
    Accept-Encoding: gzip, deflate
    Content-Length: 166
    Connection: keep-alive
    cache-control: no-cache
    
    
    Content-Disposition: form-data; name="bucketName"
    
    2
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--,
    Content-Disposition: form-data; name="bucketName"
    
    2
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--
    Content-Disposition: form-data; name="cname"
    
    1
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--,
    Content-Disposition: form-data; name="bucketName"
    
    2
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--
    Content-Disposition: form-data; name="cname"
    
    1
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--
    Content-Disposition: form-data; name="file"; filename="/C:/Users/zhaoyanjiang-pc/Pictures/59224cf41dd06_610.jpg
    
    
    ------WebKitFormBoundary7MA4YWxkTrZu0gW--
    

    单元测试用例:

     @Test
        public void getConnection(){
            String result = HttpRequests.getInstance("https://service.emmazhang.top/files/db/list")
                    .addHead("111","111").addParams("size","2").addParams("start","1").doPost();
            log.debug(result);
        }
        @Test
        public void getConnection1(){
            String result = HttpRequests.getInstance("http://wwww.emmazhang.top/files/get")
                    .addHead("111","111").addParams("name","1157187738680823810.png").doGet();
            log.debug(result);
        }
    
        @Test
        public void getConnection2(){
            HttpRequests requests = HttpRequests.getInstance("http://localhost:8080/test/formTest")
                    .addHead("111","111").addParams("cname","1157187738680823810.png").addParams("bucketName","11111111111");
            requests.setFile("/C:/Users/zhaoyanjiang-pc/Pictures/111.png");
            requests.setFileName("file");
            String result = requests.doPostFormData();
            log.debug(result);
        }
    

    完整的实现如下:

    package com.zhao.net;
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    /**
     * @program: test
     * @description:
     * @author: zhaoyj
     * @create: 2019-08-26 15:10
     */
    @Slf4j
    @Data
    public class HttpRequests {
    
        public static HttpRequests getInstance(String url) {
            HttpRequests httpRequests = new HttpRequests();
            httpRequests.setUrl(url);
            return httpRequests;
        }
    
        private String file;
        private String fileName;
        private String url;
        private Map<String,String> params;
        private String contentType = "application/json";
        private Map<String,String> heads;
        private Integer connectTimeout = 15000;
        private Integer readTimeout = 60000;
        private static final String BOUNDARY_STRING = "7MA4YWxkTrZu0gW";
        public static final String BOUNDARY = "--" + BOUNDARY_STRING + "\r\n";
    
        public HttpRequests addHead(String key, String value) {
            heads = Optional.ofNullable(heads).orElseGet(HashMap::new);
            heads.put(key,value);
            return this;
        }
        public HttpRequests addParams(String key,String value){
            params = Optional.ofNullable(params).orElseGet(HashMap::new);
            params.put(key,value);
            return this;
        }
        private String getResponse(InputStream in) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 封装输入流is,并指定字符集
            int i;
            while ((i = in.read()) != -1){
                baos.write(i);
            }
            String result = baos.toString();
            return result;
        }
        private String toJSONString(Map<String,String> map){
            Iterator<Map.Entry<String,String>> i = map.entrySet().iterator();
            if (! i.hasNext()) {
                return "{}";
            }
    
            StringBuilder sb = new StringBuilder();
            sb.append('{');
            for (;;) {
                Map.Entry<String,String> e = i.next();
                String key = e.getKey();
                String value = e.getValue();
                sb.append("\"");
                sb.append(key);
                sb.append("\"");
                sb.append(':');
                sb.append("\"");
                sb.append(value);
                sb.append("\"");
                if (! i.hasNext()) {
                    return sb.append('}').toString();
                }
                sb.append(',').append(' ');
            }
        }
    
        private String createParams() {
            if(params != null && !params.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (Map.Entry<String, String> stringObjectEntry : params.entrySet()) {
                    try {
                        sb.append(stringObjectEntry.getKey()).append("=").append(URLEncoder.encode(stringObjectEntry.getValue(),"UTF-8")).append("&");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                sb.delete(sb.length() - 1, sb.length());
                return sb.toString();
            }
            return "";
        }
        /**
         * 发送get请求
         * @return 返回请求结果
         */
        public String doGet() {
            if(params != null && !params.isEmpty()) {
                url += "?";
                url += createParams();
            }
            URL u ;
            HttpURLConnection connection ;
            try {
                u = new URL(url);
                log.error(url);
                connection = (HttpURLConnection) u.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(connectTimeout);
                connection.setReadTimeout(readTimeout);
                connection.setRequestProperty("Content-Type",contentType);
                if(heads != null){
                    for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                        connection.setRequestProperty(stringStringEntry.getKey(),stringStringEntry.getValue());
                    }
                }
                InputStream is = connection.getInputStream();
                return getResponse(is);
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            } catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * 发送post请求
         * @return 请求结果
         */
        public String doPost() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                connection = getPostConnection();
                out = connection.getOutputStream();
                if(params != null && !params.isEmpty()) {
                    out.write(toJSONString(params).getBytes());
                }
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 发送post表单请求
         * @return 请求结果
         */
        public String doPostFormUrl() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                this.contentType = "application/x-www-form-urlencoded; charset=UTF-8";
                this.contentType = "multipart/form-data";
                connection = getPostConnection();
                out = connection.getOutputStream();
                if(params != null && !params.isEmpty()) {
                    out.write(createParams().getBytes());
                }
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 发送post表单请求
         * @return 请求结果
         */
        public String doPostFormData() {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            try {
                this.contentType = "multipart/form-data; boundary=" + BOUNDARY_STRING;
                connection = getPostConnection();
                out = connection.getOutputStream();
                StringBuilder sb = new StringBuilder();
                if(params != null && !params.isEmpty()) {
                    for (Map.Entry<String, String> stringStringEntry : params.entrySet()) {
                        sb.append(BOUNDARY);
                        sb.append("Content-Disposition:form-data;name=\"");
                        sb.append(stringStringEntry.getKey());
                        sb.append("\"\r\n\r\n");
                        sb.append(stringStringEntry.getValue());
                        sb.append("\r\n");
                    }
                    out.write(sb.toString().getBytes());
                }
                if(file != null && fileName != null) {
                    StringBuilder sf = new StringBuilder();
                    sf.append(BOUNDARY);
                    sf.append("Content-Disposition:form-data;name=\"");
                    sf.append(fileName)
                    .append("\"; filename=\"")
                    .append(file)
                    .append("\"\r\n\r\n");
                    out.write(sf.toString().getBytes());
                    File f = new File(file);
                    InputStream is = new FileInputStream(f);
                    byte[] buffer = new byte[8192];
                    int count = 0;
                    while ((count = is.read(buffer)) != -1) {
                        out.write(buffer, 0, count);
                    }
                    out.write("\r\n\r\n".getBytes());
                    is.close();
                }
                out.write(("--" + BOUNDARY_STRING + "--\r\n").getBytes());
                log.error(sb.toString());
                out.flush();
                out.close();
                try(InputStream is = connection.getInputStream()) {
                    return getResponse(is);
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (MalformedURLException e) {
                log.error("the url format is err,check it ! {}",url);
                e.printStackTrace();
            }catch (ProtocolException e) {
                assert connection != null;
                log.error("the request protocol is error, check it ! {}",connection.getRequestMethod());
                e.printStackTrace();
            }catch (IOException e) {
                log.error("the I/O operation is error !");
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 发送post表单请求
         * @return 请求结果
         */
        private HttpURLConnection getPostConnection() throws IOException {
            URL u ;
            HttpURLConnection connection = null;
            OutputStream out ;
            u = new URL(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            connection.setRequestProperty("Content-Type",contentType);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            if(heads != null){
                for (Map.Entry<String, String> stringStringEntry : heads.entrySet()) {
                    connection.setRequestProperty(stringStringEntry.getKey(),stringStringEntry.getValue());
                }
            }
           return connection;
        }
    }
    
    

    后端接收时,带文件的需要实体接收,如下:

    package com.zhao.aliyun.controller;
    
    import com.baomidou.mybatisplus.core.toolkit.IdWorker;
    import com.zhao.aliyun.entity.FileEntity;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    
    /**
     * @program: aliyun
     * @description:
     * @author: zhaoyj
     * @create: 2019-08-27 10:35
     */
    @RestController
    @RequestMapping("/test")
    @Slf4j
    public class TestController {
    
        @RequestMapping(value = "/formTest",method = RequestMethod.POST)
        public Object formTest(@ModelAttribute FileEntity multipartFile){
            MultipartFile multipartFile1 =  multipartFile.getFile();
            File f = new File("d:\\test\\" + IdWorker.getIdStr() + "." + multipartFile1.getOriginalFilename().split("[.]")[multipartFile1.getOriginalFilename().split("[.]").length - 1]);
            try{
                log.error(multipartFile.getFile().getContentType());
                multipartFile.getFile().transferTo(f);
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
    
    

    转存后的文件
    微信截图20190827143201.png

    展开全文
  • 在开发中,有时候会遇到需要调用现成的接口,我们就可以使用 Apache 提供的 Java 工具类 HttpClient。 一、引入 Maven 坐标 使用 Apache 的 HttpClient 需要引入相关的 Maven 坐标,Maven 坐标如下: <!-- ...


    发送 HTTP 请求

    在开发中,有时候会遇到需要调用现成的接口,我们就可以使用 Apache 提供的 Java 工具类 HttpClient。

    一、引入 Maven 坐标

    使用 Apache 的 HttpClient 需要引入相关的 Maven 坐标,Maven 坐标如下:

    <!--        HttpClient 相关依赖-->
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.12</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient-cache -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient-cache</artifactId>
                <version>4.5.12</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.12</version>
            </dependency>
    

    二、发送 GET 请求

    不携带参数的 GET 请求的方法如下:

        /**
         * 功能描述: 使用 get 请求直接访问 url,不带参数
         *
         * @param url
         * @return: java.lang.String
         * @author: 路人WL
         * @date: 2020/4/27
         */
        public static String doGet(String url) throws Exception {
            // 创建 HttpClient 对象
            CloseableHttpClient client = HttpClients.createDefault();
    
            // 创建访问地址
            URIBuilder uriBuilder = new URIBuilder(url);
    
            // 创建 http 对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
    
            // 执行 get 请求
            CloseableHttpResponse httpResponse = client.execute(httpGet);
            // 接收回复的内容
            String result = null;
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(httpResponse.getEntity());
            } else {
                throw new Exception("发送 GET 请求失败");
            }
            client.close();
            // 获取内容
            return result;
        }
    

    三、发送 POST 请求

    1、参数是 key-value 形式

    /**
         * 功能描述: 基础 post 请求
         *
         * @param url    发送 post 请求的 url
         * @param paramsMap post 请求携带的参数
         * @return:
         * @author: 路人WL
         * @date: 2020/4/28
         */
        public static String doPost(String url, Map<String, String> paramsMap) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> paramsList = new ArrayList<>();
            // 填充参数
            paramsMap.keySet().forEach(key -> paramsList.add(new BasicNameValuePair(key, paramsMap.get(key))));
            httpPost.setEntity(new UrlEncodedFormEntity(paramsList));
    
            CloseableHttpResponse response = client.execute(httpPost);
            client.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
    

    2、参数形式为 json

    /**
         * 功能描述: 发送 POST 请求传递 Json
         *
         * @param url
         * @param json
         * @return:
         * @author: 路人WL
         * @date: 2020/4/28
         */
        public static String doPostWithJson(String url, String json) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
    
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
    
            CloseableHttpResponse response = client.execute(httpPost);
            client.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
    

    四、封装 HTTPUtil 工具类

    将上面的方法封装为 HTTPUtil 类

    package com.stormli.util;
    
    import org.apache.http.NameValuePair;
    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.client.utils.URIBuilder;
    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 java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 通过 http 协议发送请求
     *
     * @author 路人WL
     * @date 2020/4/27  
     */
    public class HttpUtil {
        /**
         * 功能描述: 使用 get 请求直接访问 url,不带 header 和 param
         *
         * @param url
         * @return: java.lang.String
         * @author: 路人WL
         * @date: 2020/4/27
         */
        public static String doGet(String url) throws Exception {
            // 创建 HttpClient 对象
            CloseableHttpClient client = HttpClients.createDefault();
    
            // 创建访问地址
            URIBuilder uriBuilder = new URIBuilder(url);
    
            // 创建 http 对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
    
            // 执行 get 请求
            CloseableHttpResponse httpResponse = client.execute(httpGet);
            // 接收回复的内容
            String result = null;
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(httpResponse.getEntity());
            } else {
                throw new Exception("发送 GET 请求失败");
            }
            client.close();
            // 获取内容
            return result;
        }
    
        /**
         * 功能描述: 基础 post 请求
         *
         * @param url    发送 post 请求的 url
         * @param paramsMap post 请求携带的参数
         * @return:
         * @author: 路人WL
         * @date: 2020/4/28
         */
        public static String doPost(String url, Map<String, String> paramsMap) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> paramsList = new ArrayList<>();
            // 填充参数
            paramsMap.keySet().forEach(key -> paramsList.add(new BasicNameValuePair(key, paramsMap.get(key))));
            httpPost.setEntity(new UrlEncodedFormEntity(paramsList));
    
            CloseableHttpResponse response = client.execute(httpPost);
            client.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
    
        /**
         * 功能描述: 发送 POST 请求传递 Json
         *
         * @param url
         * @param json
         * @return:
         * @author: 路人WL
         * @date: 2020/4/28
         */
        public static String doPostWithJson(String url, String json) throws Exception {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
    
            StringEntity entity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
    
            CloseableHttpResponse response = client.execute(httpPost);
            client.close();
            if (response.getStatusLine().getStatusCode() == 200) {
                return EntityUtils.toString(response.getEntity());
            }
            return null;
        }
    }
    
    展开全文
  • 使用Java模拟http请求.rar使用Java模拟http请求.rar
  • 使用java发送HTTP请求

    千次阅读 2017-02-14 10:04:34
    近来在写项目时调用第三方接口,发现使用第三方接口基本都要使用java程序来发送HTTP请求到第三方的服务器去获取数据,不同的第三方提供的方法不尽相同,有使用org.apache.commons.httpclient的,有使用org.apache....

    近来在写项目时调用第三方接口,发现使用第三方接口基本都要使用java程序来发送HTTP请求到第三方的服务器去获取数据,不同的第三方提供的方法不尽相同,有使用org.apache.commons.httpclient的,有使用org.apache.http.client的,有使用org.codehaus.xfire.client,还有使用org.springframework.web.client的,个人还是比较喜欢使用java原生的java.net.URL与java.net.HttpURLConnection来发送HTTP请求,所以自己写了一个方法,共飨诸君

    public static String sendHttpRequest(String url, String entity, String method) {
        BufferedReader bufferedReader = null;
        URL realUrl;
        HttpURLConnection conn = null;
        PrintWriter printWriter = null;
        String result = "";
        try {
            if ("get".equals(method)) {
                if (entity != null && !"".equals(entity)) {
                    realUrl = new URL(url + "?" + entity);
                } else {
                    realUrl = new URL(url);
                }
                // 根据url生成urlConnection对象
                conn = (HttpURLConnection) realUrl.openConnection();
               /* conn.connect();可以不明文设定连接,conn.getInputStream()会自动连接*/
            } else if ("post".equals(method)) {
                realUrl = new URL(url);
                conn = (HttpURLConnection) realUrl.openConnection();
                conn.setRequestMethod("POST");/*设定请求的方法为"POST",默认是GET */
                if (entity != null && !"".equals(entity)) {
                    // 设置是否从httpUrlConnection读入,默认情况下是true;
                    conn.setDoInput(true);
                    /*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false*/
                    conn.setDoOutput(true);
                    // Post 请求不能使用缓存
                    conn.setUseCaches(false);
                    conn.connect();
                    printWriter = new PrintWriter(conn.getOutputStream());
                    printWriter.print(entity);
                    printWriter.flush();
                }
            }else{
                throw new IllegalArgumentException("请输入正确的请求方式");
            }
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            if ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (printWriter != null) {
                    printWriter.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return result;
        }
    
    }
    测试方法如下:<特意测试了post请求,请求参数为null的情况>

    public static void main(String[] args) {
        String str = "userMobile=15539266567&usertype=0";
        System.out.println(sendHttpRequest("http://localhost:8080/mine/try", null, "get"));
        System.out.println(sendHttpRequest("http://localhost:8080/mine/your/best", str, "post"));
        System.out.println(sendHttpRequest("http://localhost:8080/mine/so/amazing", null, "post"));
    }
    在控制台打印输出,哈哈,是不是很完美。关于PUT请求与DELETE请求与POST请求类似,不再敖述。

    false
    1
    {"StageCategory":[{"id":"001","name":"第一阶段"},{"id":"002","name":"第二阶段"},{"id":"003","name":


    展开全文
  • Java如何发起http请求 前言 一、GET与POST 1.GET方法 2.POST方法 实现代码 实例演示 字符串转json 结束 前言 在未来做项目中,一些功能模块可能会采用不同的语言进行编写。这就需要http请求进行模块的调用。那么下面...
  • 使用java创建http请求

    千次阅读 2018-05-28 08:00:57
    * @param requestUrl 请求的链接 * @param requestMethod 请求方法(GET,POST) * @param outputStr 请求参数(可以使json字符串,也可以是xml) * @return str(字符串,一般是json字符串,也可以是xml字符串) */ ...
  • 使用java.net原生的HttpURLConnection类实现http的get和post请求 package com.alison.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io...
  • 创建Java sources create or replace and compile java source named pushmessage as import java.io.BufferedReader; import java.io.IOException...
  • Java发送HTTP 请求

    千次阅读 2019-03-19 15:29:25
    因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。 正文 使用须知 为了避免大家引错包我把依赖和涉及到包路径给大家 import java.net....
  • java模拟HTTP请求

    千次阅读 2015-08-11 13:52:32
    Java发送http请求 (get 与 post方法请求) Sunday, August 22nd, 2010 at 00:00 久酷 Java发送http请求 (get 与 post方法请求),以下代码经本人亲自调试可用!可以直接使用之。 注意:通过...
  • java实现HTTP请求

    2020-06-27 15:58:44
    目前JAVA实现HTTP请求的方法用的最多的有两种: 1、通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons....
  • java发送http请求

    2017-03-29 10:24:25
    使用http发送请求时遇到的问题 1. +号不显示 原因:在传输中丢失或不认 解决方式:使用了全角的+,半角的+会...3.java发送http请求给第三方 /** * 向指定 URL 发送POST方法的请求 * * @param url * 发
  • Java模拟Http请求

    2018-08-31 12:05:58
    Java模拟Http请求 使用的是org.apache.httpcomponents中的httpclient,因为post请求涉及到传输文件,所以需要使用httpmime这个包 &amp;lt;dependency&amp;gt; &amp;lt;groupId&amp;gt;org....
  • 简介:该工具类使用HttpURLConnection实现了调用http请求,同时支持调用https请求。1.实现及测试代码: import com.lenovo.m2.test.utils.StringUtil;import javax.net.ssl.*; import java.io.BufferedReader; ...
  • 在本文中,我们将向您展示一些示例,这些示例通过以下API发出HTTP GET / POST请求 Apache HttpClient 4.5.10 OkHttp 4.2.2 Java 11 HttpClient Java 1.1 HttpURLConnection(不推荐) 1. Apache ...
  • Java模拟HTTP请求2

    千次阅读 2018-10-30 21:47:49
    之前转过一篇基于HttpClient的Java模拟HTTP请求使用的第三方jar文件,这次升级JDK11之后模拟HTTP请求不需要再导入第三方jar文件了,官方扩展了java.net包,所有的HTTP请求相关类均位于java.net.http包内,示例代码...
  • java 发送http请求

    2014-11-11 10:51:21
    java发送http请求 最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet。post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求...
  • Java服务端使用HttpServer处理Http请求

    万次阅读 2017-09-06 22:36:23
    以前用Java都是编写客户端发送http请求,这次有需求做一个服务端接收客户端的http请求,并以http标准格式返回数据。在网上搜了一会,大部分都是用socket写的服务端,不符合需求。Java其实提供了一个HttpServe...
  • 简介:使用URLConnection实现了调用http请求,该方法不支持调用https请求。https调用方式可查看:HttpURLConnection实现和HttpClient实现1.使用GET方式调用http请求代码: public static String requestHttpGet...
  • 简介:该工具类使用HttpClient实现了调用http请求和支持https的调用方式。1.使用HttpClient实现调用http和https请求: import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache....
  • java模拟Http请求

    2016-10-21 09:57:17
     使用java编程模拟http请求以post方式大致分为以下步骤:  一、通过抓包工具(或者浏览器自带的调试工具)来获取http请求的具体信息,如Request URL、User-Agent、Accept-Language、Accept-Encoding、cookie等...
  • Java发出HTTP请求踩坑

    2020-11-28 12:14:00
    Java发出HTTP请求踩坑 1.功能需求 通过对方提供的接口进行访问,将拿到的数据转为指定格式放入数据库中,在get请求中经常需要携带参数以及token验证,快速访问http地址获取内容方法 一次搞定get、post请求,复制即可...
  • 在项目中有过这么一次要求,就是在我本次项目中要使用java调用别人的接口,使用...//http请求============== protected static InputStream httpRead(String url){ Debug.info("==========Graphic httpRead come i...
  • java使用NIO构造http请求

    千次阅读 2014-09-26 10:41:27
    使用java的NIO来构造http请求体,并且取得响应内容。 package com.test.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset...
  • 记录一下,使用http获取插件token时使用的代码。 package util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net....

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 9,242
精华内容 3,696
关键字:

java使用http请求

java 订阅