简体   繁体   English

java 如何将 Multipart/Form-data 发送到 rest 服务

[英]java how to send Multipart/Form-data to rest service

I know that this has been asked so many times.我知道这个问题已经被问过很多次了。 It looks like a fragile thing.它看起来像一个脆弱的东西。 I am trying to send form-data to my REST end-point.我正在尝试将表单数据发送到我的 REST 端点。 It keeps saying the following on the server side:它一直在服务器端说以下内容:

org.apache.tomcat.util.http.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly

Authorization works, I am getting a JWT.授权有效,我得到了 JWT。 MakeRequest does not work. MakeRequest 不起作用。 The something in postman works. postman 中的东西有效。 After some research and trial/error: I have found that the boundary value does not;经过一些研究和试验/错误:我发现边界值没有; this is even if I respect RFC即使我尊重 RFC

This is the raw request: Note(I have removed the image partly because it was too long.)这是原始请求:注意(我删除了图像,部分原因是它太长了。)

-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="request_config"
Content-Type: text/plain; charset=UTF-8

{
  "respondent_identification": {
    "search_strategy": {
      "questionnaire_id": 221,
      "terminal_id": 285,
      "identifier": fqql7d7o62,
      "fail_on_empty": false,
      "searchStrategy":"ExternalIdentifier"
    }
  },
  "answers": null,
  "dynamic_values": [
    {
      "date_created": "2021-02-24T02:15:12-05:00",
      "data_key": "glissade_18",
      "data_values": [
        "ref:file1",
        "ref:file2","David St-Ciboire","7.5"
      ]
    }
  ]
}
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file1"; filename="c1.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary

���� JFIF  H H  �� C        



�� C

�� ��" ��               
�� �   } !1AQa"q2���#B��R��$3br�    
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������            
�� �  w !1AQaq"2�B����  #3R�br�
$4�%�&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������   ? ��f�jֺ u|�n�=��&�l�i�F���D%���rO<kf����R:���Y��v�    ��,Jғ���� q^l_>�=9�;0�|[~��?63(��Uq���?{=�FA<�5%��k���H�gD��G8�qsS6��Z{x�e��W��3����H�۔洛��  �'k�� �+��+[�?YeK���o����=1�:�W^��V���$�&f�nثZ��ymmla��+~����O�k99��N�ճrIg��B�o�}�Z0=��㊍%ԥe�6�$��;O�8���}�D��k�bXcUx{``r���EI��{3�o6�su�|SE1)*z��#����ORڄ�U���<1�Ǘg ��*(��i$�V����:|���k���-�id��9�t`I�*��h�%��t�;�,g;G$�   �UW�mdLyou���D�oF�<�Q���-Iqw��5�[���\������HϮ+��l<E�*��,0oiH�5/�����.͔�o�S�f�T��e��m���I��Qm/8��5 c�����m��ŖE8�s����[��6g��m�g?5�b��$T�L��,��īn1%���#��}�#ɻl���O�x�H.>�i��3`���ձ����#S���β�Vֱ2]�BC P���ҼMM��f��c�f*��#&���@�/]�X�n%���
��-��{*�    ��CǃO��������ls���!��%��f��
����:r`��yS����ڎ�~�4�ަ��ys�����O5�;~Ps��n+���_�W�5���z�jš:db�,e���}�����a�� b�^OW%����8��&�*����5�O���� h?��*;{���y&k�� ��1�+�/`U~q�y�o�;b4�
�s0�/Bɷ�:ζ�放#���~��v�,vj����j�Υ0On��b��3�f���6vH���G#5j"F�~��Sk�F��j7�m��u��H��M-@Ѹ1H�g���<�=?t̤go8�.*���Ha���;����c�'��@�*�I��@�1Z68 ~]jkǁb\`��Ҩ�\�^�n-Qg|k��J� S��E��e�' w��ݝ�.Oʼ��j(Xnwr}j   �?�j)&P����u�~�:;� ��Ԃ@�7���5�ݻw�G��~��@ѥ���{sKI��8�P}:�γ�������ku�a�9�a� �OҤX݇Z����I?Jk]K��lz���y�>��q�j��K�"6���3ܑ�Ls�SW�Z�м�k/�t�9n~��?0+�b�i�&���Mq+K#7�3������ i���|�S�/�_MdBO,Y� >��e��`��O=+�nV�J� -��c��}j��lpj�-��sg��8�Q�L���0 �Wf,��N�Y�l4+Df�R���@�����ҝ>D���m>�v�k
A_���?c

-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file2"; filename="a12.jpg"
Content-Type: image/jpeg
Content-Transfer-Encoding: binary

���� JFIF  H H  �� C        



�� C

�� ��" ��               
�� �   } !1AQa"q2���#B��R��$3br�    
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������            
$��*�5���V��m��3G� �8ܪ��;c?J����T�i��+��ċ"��sM��O����׬#�h�>s�� �3�  aӵr��}V�I�]<�Gaks��_G��u\)�'#�y���n�p�_C�0s�1���W�{��Eey㾽���g�  ǨS�"���&�����_��������G��6�׈��F�հ+���o�X��`�I�K�k~%�!PYX��8 �?�5�tW������f�?
�{M��W��a8I���8=(�w���V����.C>�lw�{�+bܝބU�B� v �[�TY    � V�>���癃m�� �x��   ?�i� i�_n����5�?�9�&�vp�\. �7sW
��۸ =3T���nV���D�ߣTJM��ZE���U"��ʋ��09��|��vV=�y�G��w�������:��b�:g�*�԰�;��ڴ�Y>l�oƳo��'1ɷک;�H��[f��lzri�"v�.[��D��$�lw,���$�6���B���X;��&�`�>C듊�ݢ���jeR����N�:I�@��05����5i1��\��W�2��z��W�|N�~Ǯ˜��zc��D�QW<��n��o<w���}����D�*�� Vw�k�� ��� ��)�F*K�@˅��20[����7sP�Ġ�� �b��դ9��/��-�L���o����i�:��ad_�UR�={�ӕ{^Sf�95���w
�8i�N�K4�FY&��i���O^���vgK��isVj����e��5��>�7��)<=jl�k�H��М�ts��<�d�º_Y)�/g�2b���?1��$�<~U�G{�SM�~�O��%����5+�el����X�?{���6�2_@;|WO�y!�V���[8�+��s?�� d�qep��G���\wA�b�t�jYC.�!i�:��:�X$w�N1XC \I���Ԯw���+����+�+���&  �����:��_s�W�Ӯ%\Es7�;��W�UB�4*6�$ch�5U|G`�x�W���D�wA� .Q[�Zt�T�cs+U��������� �9�� 
௭lc�.��dVh|IN��ʄ'�g�k�<U7��/-�X�`Q�m�r�ט��m���:L�P��\����o<LD���㳭K�f��=Q7��.� Z��E����ҽ�)`�M�ɱ�;��'�5��ǯ�����O�/Ɨkv$�/�v� k�s�
)$ �-�׸��Z���xa�B�˕�^W�[w>�r03�_/��{d6�i�����\[�;�9�#����1��-i�G�N����5���;`��ė���  (D�� ��
�Ű~'x'� 
;O�9QI�?���|K�G�V��r�Yve}΢9��Q�=nTҸ������ߊ~_��-?��E'į�����_6C�+C���Nϰ������I�7����1��?v�|K�i'�� 
���������ԏ���� �E�4{�V��Lc�ң����P�㱮^���'| ������2����&[�7����'���r�+�O2�t����c-ӡ5SK�����2氵�
6��'��?�?k� �*���G�/��O~:��� �Ҷ�s.�Q��S�+�p1�i��$v�7��>��~#xK����_�.������^P?�a��R�Y    ���a4���1Vm�N���n��^|O�]''�W����Z��Kc�;�Z����r`� ��j3� �)r��̎�&x�^��-���\�|R�]�>(x,{Z��_�Z��x%���V�� jQ��@�s��
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="name"
Content-Type: text/plain; charset=UTF-8

Robert
-----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="lastName"
Content-Type: text/plain; charset=UTF-8

Mano
-----WebKitFormBoundary7MA4YWxkTrZu0gW--

This is my code:这是我的代码:

public class Main {

    public static void main(String[] args){
        getAuthorizationKey();
        for(int i =0;i<1;i++)
        {
            String str=makeRequest();
            while(str.equals("401")){
                getAuthorizationKey();
                str=makeRequest();
            }
        }
    }

    static DataOutputStream request = null;
    static String boundary ;
    static File processedFile = null;
    static String key;
    static HttpURLConnection con;
    private static final String LINE = "\r\n";

    private static String getAuthorizationKey() {
        StringBuilder response = new StringBuilder();;
        try {
            URL url = new URL("http://localhost:8080/login");
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setDoOutput(true);
            DataOutputStream os = new DataOutputStream(con.getOutputStream());
            os.write("{\"username\":\"dev\",\"password\":\"1234\"}".getBytes());
            os.flush();
            os.close();
            // For POST only - END

            int responseCode = con.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                key =con.getHeaderField("Authorization");
                response.append(key);


                // print result
                System.out.println(response.toString());
            } else {
                System.out.println("POST request not worked. Response Code: "+ responseCode);
            }
        }
        catch (Exception e){

        }

        return response.toString();
    }

    private static String makeRequest(){

        boundary = "---WebKitFormBoundary7MA4YWxkTrZu0gW";
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL("http://localhost:8080/multipart-form-data2");
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Authorization",key);    // essential things are set
            con.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
            request = new DataOutputStream(con.getOutputStream());

            addFormField("request_config",getRequestData());

            addFilePart("file1", randomFilePicker());

            addFilePart("file2", randomFilePicker());

            addFormField("name", "Robert");

            addFormField("lastName","George");

            request.flush();
            request.writeBytes(boundary + "--"+LINE);
            request.close();
            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { //success
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        con.getInputStream()));
                String inputLine;

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                // print result
                System.out.println(response.toString());
            }else if(responseCode == HttpURLConnection.HTTP_UNAUTHORIZED){
                response.append("401");
            }else {
                System.out.println("POST request not worked");
            }



        }catch (Exception e){
            System.out.println(e);
        }
        return response.toString();
    }

    public static void addFormField(String name, String value)throws IOException  {
        request.writeBytes("--" + boundary + LINE);
        request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+LINE);
        //request.writeBytes("Content-Type: text/plain; charset=UTF-8"+LINE);
       // request.writeBytes(this.crlf);
       // request.writeBytes(LINE);
        request.writeBytes(value+LINE);
        request.flush();
    }

    public static void addFilePart(String fieldName, File uploadFile)throws IOException {
        String fileName = uploadFile.getName();
        request.writeBytes("--" + boundary + LINE);
        request.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\""+LINE);
        request.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)+LINE);
       // request.writeBytes("Content-Transfer-Encoding: binary"+LINE);
        request.writeBytes(LINE);
        //request.writeBytes("--");
        request.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        OutputStream outputStream = con.getOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();
        request.writeBytes(LINE);
        request.flush();
    }


    public static File randomFilePicker(){

        File samplePhotos = new File("C:\\Users\\Kugan Mano\\Desktop\\sample photos");
        File[] listFic = samplePhotos.listFiles();
        File fic;
        do {
            double val = Math.random() * listFic.length;

            fic = listFic[(int) val];
        }while (processedFile!=null && processedFile.getName().equals(fic.getName()));
        processedFile = fic;
        return fic;
    }

    public static String  finishRequest() throws Exception{

        StringBuilder response = new StringBuilder();
        request.flush();
        request.close();
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("POST request not worked");
        }

        return response.toString();


    }




    private static String getRequestData(){
        return "{\n  \"respondent_identification\": {\n    \"search_strategy\": {\n      \"qId\": 221,\n      \"tId\": 285,\n      \"identifier\": fqql7d7o62,\n      \"fail_on_empty\": false,\n      \"searchStrategy\":\"ExternalIdentifier\"\n    }\n  },\n  \"reps\": null,\n  \"values\": [\n    {\n      \"date_created\": \"2021-02-24T02:15:12-05:00\",\n      \"data_key\": \"glissade_18\",\n      \"data_values\": [\n        \"ref:file1\",\n        \"ref:file2\",\"David St-Ciboire\",\"7.5\"\n      ]\n    }\n  ]\n}";
    }
}

You can incorporate MultipartFile object, as a parameter of your handler method:您可以合并MultipartFile object,作为处理程序方法的参数:

@PostMapping("/upload)
public void upload(@RequestParam("paramName") MultipartFile file) {
    InputStream is = file.getInputStream();
    //read your input stream as you wish..
}

Only thing which you will need to have as an infrastructure component, is MultipartConfigElement bean, which you register as:作为基础设施组件,您唯一需要的是MultipartConfigElement bean,您将其注册为:

@Configuration
public class AppConfig {

    @Bean
    public MultipartConfigElement multipartConfig() {
        MultipartConfigFactory f = new MultipartConfigFactory();

        //f.setMaxFileSize(DataSize.ofBytes(200000)); //applies to one file size
        //f.setMaxRequestSize(DataSize.ofBytes(500000)); //applies to total size of HTTP request

        return f.createMultipartConfig();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM