python API请求到Java的转换不起作用

python API请求到Java的转换不起作用,java,python,api,Java,Python,Api,我正在尝试使用Java复制一个调用远程服务的非常简单的Python函数。我没有服务文档。下面是Python代码: def sendImage(addr, image_path): image = open(image_path, 'rb').read() files = { 'image': ('Image.jpg', image, 'image/jpg') } response = requests.post(addr, files = files) print

我正在尝试使用Java复制一个调用远程服务的非常简单的Python函数。我没有服务文档。下面是Python代码:

def sendImage(addr, image_path):
    image = open(image_path, 'rb').read()
    files = { 'image': ('Image.jpg', image, 'image/jpg') }
    response = requests.post(addr, files = files)
    print(response.text)
但我似乎没法让它发挥作用。以下是我目前的Java代码:

try {

    URL url = new URL(request);
    HttpURLConnection connection = (HttpURLConnection) url
            .openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "image/jpeg");
    connection.setConnectTimeout(Constants.TIMEOUT);
    connection.setReadTimeout(Constants.TIMEOUT);
    try (OutputStream out = connection.getOutputStream()) {
        IOUtils.copy(image, out);
    }
    try (InputStream in = connection.getInputStream()) {
        Map<String, String> originalResponse = mapper.readValue(in, TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, String.class));
    }

}
catch (Exception e) {
    e.printStackTrace();
}
然后我得到了一个“400:Bad Request”的响应


为什么这不起作用,我怎样才能使它起作用?提前感谢

response=requests.post(addr,files=files)
是(请参阅),在java代码中,您只需将文件内容作为请求主体编写即可

若您想编写代码来正确处理多部分请求,那个么请检查请求正文中必须包含的内容


我的建议是使用一些http客户端

比较网络流量以查看请求中的差异。你收到了400个错误的请求。K,下载wireshark,看看有什么好主意!谢谢,我将研究它并报告在修改了一点示例代码之后,我让它开始工作了。谢谢你的帮助!
try (InputStream in = connection.getInputStream()) {