使用java发送Http请求

使用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

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值