【问题标题】:unable to post multipart form data json request无法发布多部分表单数据 json 请求
【发布时间】:2026-01-11 17:25:08
【问题描述】:

我正在尝试 post multipart form-data 在 java 中向 api 请求。我收到400 http 错误代码。下面是我春天的终点:

spring boot api

@org.springframework.web.bind.annotation.PostMapping(value="register2")
public ResponseEntity<CoreResponseHandler> doRegister2(@RequestPart String json)  { 
System.out.println("~~~~~~     "+json+"   ~~~~~~"); 
    return null;
}

使用上述 api 的核心 java 代码

  import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8012/register2");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
            conn.setRequestProperty("charset","utf-8");
            conn.setRequestProperty("Content-Disposition","form-data;name='json'");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            JSONObject jsonObject = buidJsonObject();
            setPostRequestContent(conn, jsonObject);
            conn.connect();
            System.out.println(conn.getResponseCode());
            if(conn.getResponseCode()==200){
                BufferedReader reader= new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    stringBuilder.append(line + "\n");
                }
                System.out.println(stringBuilder+" <<<<<<<<<<<<<<<<<<<<<<<<<" );
                jsonObject=new JSONObject(stringBuilder.toString());    
            }
            else{
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    stringBuilder.append(line + "\n");
                }
                System.out.println(stringBuilder+" <<<<<<<<<<<<<<<<<<<<<<<<<" );
                System.out.println("ERRORERRORERRORERRORERRORERRORERRORERRORERROR"+conn.getResponseCode());
            }

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

    }

    private static  JSONObject buidJsonObject() throws JSONException {

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("username", "13338912");
        jsonObject.accumulate("encryptedPassword", "encpass");
        jsonObject.accumulate("name",  "fish");
        jsonObject.accumulate("email",  "fish@fish.com");
        jsonObject.accumulate("status",  "active");


        return jsonObject;
    }

    private static void setPostRequestContent(HttpURLConnection conn, 
            JSONObject jsonObject) throws IOException {

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();
        os.close();
    }

}

下面是我得到的输出:

输出

400

白标错误页面

此应用程序没有 /error 的显式映射,因此您将此视为后备。

Tue Oct 09 13:51:00 IST 2018There was an unexpected error (type=Bad Request, status=400) .必需的请求部分“json”不存在 我 don't 想使用 3rd 方依赖项,例如 okkhttp 等。

我的逻辑哪里错了。请纠正我。为什么我没有获得http 状态200

~~~~~~~~~~~~~问题好像无解~~~~~~~~~~~~~

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:
    @org.springframework.web.bind.annotation.PostMapping(value="register2" ,consumes = MediaType.APPLICATION_JSON, 
                    produces = MediaType.APPLICATION_JSON)
    public ResponseEntity<CoreResponseHandler> doRegister2(@RequestPart String json)  { 
    System.out.println("~~~~~~     "+json+"   ~~~~~~"); 
        return null;
    }
    

    这也是一个解决方案,请尝试这个

    【讨论】:

    • 内容类型 'multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'不支持
    • 如果我将内容类型更改为application/json,则会得到更多信息Could not parse multipart servlet request; nested exception is javax.servlet.ServletException: org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn&amp;#39;t contain a multipart/form-data or multipart/mixed stream, content type header is application/json
    • 删除produces= MediaType.APPLICATION_JSON 并注释块{ conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); conn.setRequestProperty("charset","utf-8"); conn.setRequestProperty("Content-Disposition","form-data;name='json'"); }
    • 完成.. 错误现在There was an unexpected error (type=Unsupported Media Type, status=415).&lt;/div&gt;&lt;div&gt;Content type &amp;#39;application/x-www-form-urlencoded&amp;#39; not supported
    • MediaType.APPLICATION_JSON 导致编译时错误。它指出:The value for annotation attribute PostMapping.consumes must be a constant expression
    最近更新 更多