JAVA POST 请求带有文件和参数的 MultiFormData

我正在尝试使用“multipart/form-data”发出 POST 请求,我需要发布一个文件(下面的代码)和 4 个参数(名称、类别...)所有字符串。


我已经可以使用下面的代码发送文件,但不能使用参数。


    // open a URL connection to the Servlet

    FileInputStream fileInputStream = new FileInputStream(sourceFile);

    URL url = new URL(upLoadServerUri);


    // Open a HTTP  connection to  the URL

    conn = (HttpURLConnection) url.openConnection();

    conn.setDoInput(true); // Allow Inputs

    conn.setDoOutput(true); // Allow Outputs

    conn.setUseCaches(false); // Don't use a Cached Copy

    conn.setRequestMethod("POST");

    conn.setRequestProperty("Connection", "Keep-Alive");

    conn.setRequestProperty("ENCTYPE", "multipart/form-data");

    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    conn.setRequestProperty("fileToUpload", fileName);


    dos = new DataOutputStream(conn.getOutputStream());


    dos.writeBytes(twoHyphens + boundary + lineEnd);

    dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\";filename=" + fileName + "" + lineEnd);

    dos.writeBytes(lineEnd);


    // create a buffer of  maximum size

    bytesAvailable = fileInputStream.available();


    bufferSize = Math.min(bytesAvailable, maxBufferSize);

    buffer = new byte[bufferSize];


    // read file and write it into form...

    bytesRead = fileInputStream.read(buffer, 0, bufferSize);


    while (bytesRead > 0) {


        dos.write(buffer, 0, bufferSize);

        bytesAvailable = fileInputStream.available();

        bufferSize = Math.min(bytesAvailable, maxBufferSize);

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);


    }


但是服务器从来不注册参数,我该如何解决这个问题?


慕村9548890
浏览 374回答 1
1回答

交互式爱情

也许您应该POST像 forrowing 演示代码一样构建请求?希望能帮助到你。### Send a form with the text and file fieldsPOST https://httpbin.org/postContent-Type: multipart/form-data; boundary=WebAppBoundary--WebAppBoundaryContent-Disposition: form-data; name="Name"myName--WebAppBoundaryContent-Disposition: form-data; name="category"myCategory--WebAppBoundaryContent-Disposition: form-data; name="data"; filename=".gitignore"Content-Type: application/json< ./.gitignore--WebAppBoundary--<> 2019-09-23T045805.200.json###
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java