当前位置:   article > 正文

【问题解决】HttpURLConnection如何以POST的方式发送请求,传递form表单格式的数据到外部接口

【问题解决】HttpURLConnection如何以POST的方式发送请求,传递form表单格式的数据到外部接口

JAVA对接外部接口(无视凭证)

问题点:

  • 给到图片URL,需要将图片先下载下来,然后以流的形式(form表单的数据格式)传给外部接口
  • 对方域名证书过期
package com.jeesite.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

public class FileUpload {

    public static void main(String[] args) {
        String imgURL = "你的图片地址";
        String FILE_UPLOAD_URL = "外部接口地址";
        String token = "请求接口校验的token";

        try {
            //处理图片链接获取名字方法工具类,可以忽略
            String imgName = getImgName(imgURL);

            // 忽略证书验证(就是这一段)
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                    }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

            // 请求地址
            URL url = new URL(FILE_UPLOAD_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            //这个可要可不要,看自己
            connection.setRequestProperty("Cookie", "SESSION=MzVhOTJlMzMtZmZjMy00M2Y5LTk1NDAtNDNlMzVjMWVlMTIw");
            //注意数据格式
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
			//用于分隔多个实体(如文件、表单字段等)的标识符(HTTP协议中,不太了解的话自行知识填充)
            String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
            OutputStream outputStream = connection.getOutputStream();

            // 文件部分
            outputStream.write(("--" + boundary + "\r\n").getBytes());
            outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + imgName + "\"\r\n").getBytes());
            outputStream.write(("Content-Type: image/png\r\n\r\n").getBytes());
            InputStream inputStream = new URL(imgURL).openStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.write(("\r\n").getBytes());

            // parentId部分
            outputStream.write(("--" + boundary + "\r\n").getBytes());
            outputStream.write(("Content-Disposition: form-data; name=\"parentId\"\r\n\r\n").getBytes());
            outputStream.write(("huanwei\r\n").getBytes());

            // name部分
            outputStream.write(("--" + boundary + "\r\n").getBytes());
            outputStream.write(("Content-Disposition: form-data; name=\"name\"\r\n\r\n").getBytes());
            outputStream.write((""+imgName+"\r\n").getBytes());

            // 结束
            outputStream.write(("--" + boundary + "--\r\n").getBytes());
            outputStream.flush();
            outputStream.close();

            // 读取响应
            int responseCode = connection.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            JSONObject jsonObject = JSON.parseObject(response.toString());
            System.out.println(jsonObject);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getImgName(String imgURL) {
        return imgURL.substring(imgURL.lastIndexOf("/") + 1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107

闹了个笑话,在和三方对接的时候我一直连不通对方的接口,甚至一度怀疑他们的接口有问题,差点吵起来。。后面发现自己电脑连了VPN,尼玛!断了一下接口就通了 服了= =

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/731700
推荐阅读
相关标签
  

闽ICP备14008679号