gpt4 book ai didi

java - 使用 HttpUrlConnection 发送图像文件时出现 HTTP_BAD_REQUEST 错误

转载 作者:行者123 更新时间:2023-12-01 10:34:36 24 4
gpt4 key购买 nike

我在使用 httpurlconnection 将图像发送到我的服务器时遇到问题。我已阅读Android documentation另一个 HttpUrlconnection implementation但我不知道哪里做错了,因为我收到了 HTTP_BAD_REQUEST 错误代码(400)。我在下面的代码中缺少什么重要的东西?

我的响应代码总是返回 400,但我的链接没问题,因为我能够使用 httpclient 实现此目的

 link = "my link.com";

try {
URL url = new URL(link);

connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestProperty("Content-Type", "image/jpeg");

BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
FileInputStream stream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead =stream.read(buffer ,0 ,buffer.length)) != -1){
outputStream.write(buffer);
outputStream.flush();
}
outputStream.flush();

responseCode = connection.getResponseCode();

最佳答案

我认为问题在于图像如何添加到输出流。所有连接配置步骤看起来都不错。

我最近尝试了这个方法,效果很好:

https://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/

包装在 AsyncTask 中也是一个好习惯。我注意到 MultipartEntity 现已弃用,但您可以用 MultipartEntityBuilder 替换。

更新

要监听文件上传事件并更新进度条,您可以重写任何 HttpEntity 实现的 writeTo 方法,并在写入输出流时计算字节数。

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://www.google.com/sorry");

MultipartEntity outentity = new MultipartEntity() {

@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CoutingOutputStream(outstream));
}

};
outentity.addPart("stuff", new StringBody("Stuff"));
httppost.setEntity(outentity);

HttpResponse rsp = httpclient.execute(httppost);
HttpEntity inentity = rsp.getEntity();
EntityUtils.consume(inentity);
} finally {
httpclient.getConnectionManager().shutdown();
}

static class CoutingOutputStream extends FilterOutputStream {

CoutingOutputStream(final OutputStream out) {
super(out);
}

@Override
public void write(int b) throws IOException {
out.write(b);
System.out.println("Written 1 byte");
}

@Override
public void write(byte[] b) throws IOException {
out.write(b);
System.out.println("Written " + b.length + " bytes");
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
System.out.println("Written " + len + " bytes");
}

}

更新如果您想根据 http 进度更新进度条,此链接提供了一个很好的示例

Link

关于java - 使用 HttpUrlConnection 发送图像文件时出现 HTTP_BAD_REQUEST 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34849985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com