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您究竟在哪里使用前三个属性? –