2013-08-28 4 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

실제로 출력 스트림에 아무 것도 쓰지 않았습니다. 또한 JSON 텍스트를 보내지 않고 자바 객체 그래프를 직렬화하기위한'DataOutputStream'을 사용해서는 안됩니다. –

+0

@ user2724130 정확히 처음 세 속성을 사용합니까? –

답변

2

DataOutputStream은 기본 유형 작성 용입니다. 이로 인해 추가 데이터가 스트림에 추가됩니다. 왜 연결을 그냥 플러시하지 않는거야?

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

편집 :

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

가 보라 : 또한 당신이 아마 더 같은 일을 할 수 있도록 당신이 실제로, 귀하의 게시물 데이터의 작성하지 한 나에게 발생

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에서 가져온 것입니다. blog이며 표준 Java SE 및 Android에서 작동해야합니다.

관련 문제