使用httpurlconnection將圖像發送到我的服務器時出現問題。我已閱讀Android documentation和另一個HttpUrlconnection implementation但我不知道自從我得到HTTP_BAD_REQUEST錯誤代碼(400)以來,它在做錯了什麼。我在下面的代碼中缺少什麼重要的東西?使用HttpUrlConnection發送圖像文件時發生HTTP_BAD_REQUEST錯誤
我的回答的代碼始終返回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();
可以在服務器處理的Content-Type =圖像/ JPEG ?嘗試使用某個控制檯或REST客戶端來測試您的請求,以確定您的請求是否正確。我認爲它應該是Content-Type multipart/form-data – CyberAleks
看到這篇文章http://stackoverflow.com/questions/8659808/how-does-http-file-upload-work – CyberAleks
@CyberAleks我的服務器可以處理,因爲上午能夠使用相同的內容類型使用httpclient –