Java 无法使用HttpPost上载文档

Java 无法使用HttpPost上载文档,java,Java,我试图使用以下代码将文档从本地计算机上载到Http,但收到Http 400错误请求错误。我的源数据是Json格式的 用于编写基本类型。这会导致它向流中添加额外的数据。你为什么不冲洗一下连接 connection.getOutputStream().flush(); connection.getOutputStream().close(); 编辑: 我还想到,您实际上还没有编写任何post数据,因此您可能需要一个更像: OutputStreamWriter wr = new OutputStre

我试图使用以下代码将文档从本地计算机上载到Http,但收到Http 400错误请求错误。我的源数据是Json格式的

用于编写基本类型。这会导致它向流中添加额外的数据。你为什么不冲洗一下连接

connection.getOutputStream().flush();
connection.getOutputStream().close();
编辑:

我还想到,您实际上还没有编写任何post数据,因此您可能需要一个更像:

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(buffer.toString());
wr.close();
用于编写基本类型。这会导致它向流中添加额外的数据。你为什么不冲洗一下连接

connection.getOutputStream().flush();
connection.getOutputStream().close();
编辑:

我还想到,您实际上还没有编写任何post数据,因此您可能需要一个更像:

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(buffer.toString());
wr.close();

了解apache http库,这将在这方面有很大帮助:

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL); 
         FileBody bin = new FileBody(file);
         MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
         reqEntity.addPart("myFile", bin);
         post.setEntity(reqEntity);  
         HttpResponse response = client.execute(post);  
         HttpEntity resEntity = response.getEntity();  

         if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }

} catch (Exception e) {
    e.printStackTrace();
}

上面的示例取自my,它应该可以与标准Java SE以及Android一起使用。

了解一下apache http库,这将在这方面有很大帮助:

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL); 
         FileBody bin = new FileBody(file);
         MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
         reqEntity.addPart("myFile", bin);
         post.setEntity(reqEntity);  
         HttpResponse response = client.execute(post);  
         HttpEntity resEntity = response.getEntity();  

         if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }

} catch (Exception e) {
    e.printStackTrace();
}

上面的示例取自my,它应该可以与标准Java SE以及Android一起使用。

您实际上还没有向输出流写入任何内容;另外,您不应该使用DataOutputStream(用于序列化Java对象图),也不应该发送JSON文本。@user2724130前三个属性具体在哪里使用?您实际上没有向输出流写入任何内容;另外,您不应该使用DataOutputStream(用于序列化Java对象图),也不应该发送JSON文本。@user2724130前三个属性在哪里使用?