2013-08-28 138 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一起工作。