1

我正在尝试使用以下代码将文档从本地计算机上传到 Http,但我收到 HTTP 400 Bad request 错误。我的源数据在Json.

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();
}
4

2 回答 2

2

DataOutputStream用于编写原始类型。这会导致它向流中添加额外的数据。你为什么不只是刷新连接?

connection.getOutputStream().flush();
connection.getOutputStream().close();

编辑:

我还发现您实际上并没有编写任何帖子数据,因此您可能想要更像:

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(buffer.toString());
wr.close();
于 2013-08-28T06:34:12.207 回答
2

Have a look into apache http libraries which will help a lot with that:

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();
}

The example above is taken from my blog and it should work with standard Java SE as well as Android.

于 2013-08-28T06:40:06.997 回答