1
我想從本地機器上傳文件到Http使用下面的代碼,但我得到HTTP 400錯誤的請求錯誤。我的源數據是Json
。無法上傳文件使用HttpPost
URL url = null;
boolean success = false;
try {
FileInputStream fstream;
@SuppressWarnings("resource")
BufferedReader bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Desktop\\test.txt"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
String request = "http://example.com";
URL url1 = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setDoOutput(true); // want to send
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false); // no user interaction
connection.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.flush();
wr.close();
connection.disconnect();
System.out.println(connection.getHeaderFields().toString());
// System.out.println(response.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
你實際上沒有寫任何東西給輸出流;你也不應該使用'DataOutputStream',它用於序列化Java對象圖,而不是發送JSON文本。 –
@ user2724130您究竟在哪裏使用前三個屬性? –