精华内容
下载资源
问答
  • 使用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

    展开全文
  • 发送 HTTP 请求 在开发中,有时候会遇到需要调用现成的接口,我们就可以使用 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请求

    千次阅读 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":


    展开全文
  • 公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容。这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过。 学习了Java两种方式,一种是用java.net...

    公司要将自己的产品封装一个WebService平台,所以最近开始学习使用Java发送Http请求的内容。这一块之前用PHP的时候写的也比较多,从用最基本的Socket和使用第三方插件都用过。

    学习了Java两种方式,一种是用java.net.URLConnection,另一种则是大名鼎鼎的HttpClient。效率上没有做深入研究,使用java.net.URLConnection比较麻烦,而HttpClient就比较惬意。

    java.net.URLConnection方法:

    private static void urlConnectionPost() {
        StringBuilder responseBuilder = null;
        BufferedReader reader = null;
        OutputStreamWriter wr = null;

        URL url;
        try {
            url = new URL(TEST_URL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(1000 * 5);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write("");
            wr.flush();

            // Get the response
            reader = new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
            responseBuilder = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line + "\n");
            }
            wr.close();
            reader.close();

            System.out.println(responseBuilder.toString());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    HttpClient方法:

    private static void httpClientPost() {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(TEST_URL);

        try {
            ContentProducer cp = new ContentProducer() {
                public void writeTo(OutputStream outstream) throws IOException {
                    Writer writer = new OutputStreamWriter(outstream, "UTF-8");
                    writer.write("");
                    writer.flush();
                }
            };

            post.setEntity(new EntityTemplate(cp));
            HttpResponse response = client.execute(post);
       
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    转载于:https://www.cnblogs.com/peijie-tech/p/3543387.html

    展开全文
  • 创建Java sources create or replace and compile java source named pushmessage as import java.io.BufferedReader; import java.io.IOException...
  • 相比于直接使用Httpclient您不再用写一大堆重复的代码了,而是像调用本地方法一样去发送HTTP请求。 文档和示例: Forest有哪些特性? 以Httpclient和OkHttp为后端框架 通过调用本地方法的方式去发送Http请求, 实现了...
  • 在本文中,我们将向您展示一些示例,这些示例通过以下API发出HTTP GET / POST请求 Apache HttpClient 4.5.10 OkHttp 4.2.2 Java 11 HttpClient Java 1.1 HttpURLConnection(不推荐) 1. Apache ...
  • 1.之前在做外部接口的时候,因为都是都有demo示例代码,所以也没太在意使用java发送http请求的内容,无意中发现使用项目中的工具类 HttpUtil发送post请求的时候 出现问题,出现了接口参数为空的情况,因为时间原因...
  • JDK中提供了一些对无状态协议请求HTTP)的支持,下面我就将我所写的一个小例子(组件)进行描述:首先让我们先构建一个请求类(HttpRequester)。该类封装了JAVA实现简单请求的代码,如下:import java.io....
  • 使用Java发送请求

    2019-05-26 11:22:45
    使用Java发送Http请求 public static JSON sengGet(Map map) { try { String date = MakeParameters.formatIso8601Date(); String url = makeMap(map); CloseableHttpCli...
  • java发送http请求

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

    2018-03-28 11:01:00
    在java中,我们发送http请求(get、post) 主要有两种方法 使用Java原生HttpURLConnection 使用第三方库,例如 Apache的HttpClient库 HttpURLConnection 下面的代码分别是使用 get 进行 http 访问和 使用 post 进行 ...
  • Java发送HTTP 请求

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

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

    2019-10-09 07:06:50
    最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL... 在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。 下...
  • 两种方法都可以发送 HTTP 请求,第一种是 Java 原生的,因此使用起来相对麻烦一些,第二种是通过第三方的包来实现,这个包是 Apache 旗下的专门用来发送 HTTP 请求的 HttpClient 包,是对 Java 原生的 ...
  • Java 实现发送Http请求

    千次阅读 2016-08-12 15:59:23
    最近需要一个短信业务的接口,发送http请求来发送短信,因为网上给的代码混乱不统一,自己实现了一个,以便自己以后自己使用java发送http请求。import org.apache.commons.httpclient.Header; import org.apache....
  • JAVA发送HTTP请求方式总结

    万次阅读 多人点赞 2018-05-30 14:40:21
    java 发送HTTP请求方式总结 源代码:http://github.com/lovewenyo/HttpDemo 1. HttpURLConnection 使用JDK原生提供的net,无需其他jar包; HttpURLConnection是URLConnection的子类,提供更多的方法,...
  • Java发送Http请求的一般步骤

    千次阅读 2019-04-29 14:51:41
    最近在使用百度地图和百度AI的开发API,经常需要发送http请求,在这里记录一下java发送Http请求的步骤。希望对大家有用。 了解Http报文结构 首先介绍Http协议的结构。请求报文和响应报文都是由以下部分组成: ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,298
精华内容 919
关键字:

使用java发送http请求

java 订阅