2013-08-28 92 views
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(); 
} 
+0

你實際上沒有寫任何東西給輸出流;你也不應該使用'DataOutputStream',它用於序列化Java對象圖,而不是發送JSON文本。 –

+0

@ user2724130您究竟在哪裏使用前三個屬性? –

回答

2

DataOutputStream用於寫入基本類型。這會導致它將額外的數據添加到流中。你爲什麼不直接沖洗連接?

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

編輯:

它也發生,我認爲你還沒有真正寫入您的任何職位的數據,所以你可能要更像一個東西:

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

看一看進入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(); 
} 

上面的例子取自我的blog,它應該與標準的Java SE以及Android一起工作。