HTTP表单数据POST错误:请求被拒绝,因为找不到多部分边界(Java)

cbwuti44  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(195)

问题的过程:

1.我试图通过发送一个表单数据得到响应,这里是结果和Postman的详细信息(成功地在Postman中获得数据):
1.有一个错误抛出:“请求被拒绝,因为没有找到multipart边界“

问题详情:

这是请求头

this is the Postman request details

这是请求体

this is the request body

HttpUtil.java相关方法如下:

public static String PostFormdata(String url, Map<String, String> map) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    for(String key:map.keySet()){
        builder.addTextBody(key, map.get(key));
    }
    String result = null;
    try {
        HttpPost httpPost = new HttpPost(url);
        HttpEntity multipart = builder.build();
        httpPost.setHeader("Content-Type", "multipart/form-data");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setConfig(requestConfig);
        httpPost.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        HttpEntity httpEntity = response.getEntity();
        result = EntityUtils.toString(httpEntity, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

以下是我的用法:

Map<String, String> params = new HashMap<String, String>();

params.put("username", "user01");
params.put("password", "abcd");
params.put("entryid", "111");
params.put("beginDate", "2023-08-01");
params.put("endDate", "2023-10-06");

Map<String, String> param = new HashMap<String, String>();
param.put("params", params.toString());

String result = HttpClientUtils.PostFormdata(url, param);

我想从POST请求中获得正确的结果

6kkfgxo0

6kkfgxo01#

我觉得,我们可以更好地重新设计你发布的API。在header中发送json kind数据不正确。它必须是一个键值对,而不是一个带有params键的json。要么在header中发送每个数据,要么在body中放置为JSON

np8igboo

np8igboo2#

试着注解掉这一行:httpPost.setHeader("Content-Type", "multipart/form-data");
或者尝试在MultipartEntityBuilder中设置边界并将其添加到http头:

String boundary = "custom-boundary";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setBoundary(boundary);
httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

相关问题