2012-07-18 4 views
4

와 양식을 제출합니다. 이 잘 작동사용 HttpClient를 POST 내가이 같은 형태의 HTML 형식을 업로드

HttpHost host = new HttpHost("localhost", 3000, "http"); 
HttpPost httpPost = new HttpPost("/products"); 
List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>(); 
data.add(new BasicNameValuePair("product[name]", "Product1")); 
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8"); 
httpPost.setEntity(entity); 
HttpResponse postResponse = httpClient.execute(host, httpPost); 

, 그 이름이 "제품 1"새로운 제품을 만들 수있다 : 여기에 내가 이미 가지고있는 것입니다. 그러나 나는 업로드 부분을 다루는 방법을 모른다. 나는 이런 모습을하고 싶습니다 :

data.add(new BasicNameValuePair("product[name]", "Product1")); 

대신 "Product1"이 파일입니다. HttpClient의 설명서를 읽었을 때 문자열 만 있다고합니다.

누구든지 업로드 부분을 처리하는 방법을 알고 있습니까?

+1

체크 아웃 http://stackoverflow.com/questions/1378920/how-can-i-make-a-multipart-form-data-post-request-using-java – jfocht

+0

그래서 해결책은 대신 MultipartEntity를 사용하는 것입니다. UrlEncodedFormEntity :-) – qusr

답변

8

종속 관계 :

<dependency> 
<groupid>org.apache.httpcomponents</groupid> 
<artifactid>httpclient</artifactid> 
<version>4.0.1</version> 
</dependency> 

<dependency> 
<groupid>org.apache.httpcomponents</groupid> 
<artifactid>httpmime</artifactid> 
<version>4.0.1</version> 
</dependency> 

코드 :

HttpClient client = new DefaultHttpClient(); 
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1); 
HttpPost post = new HttpPost(url); 
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
// For File parameters 
entity.addPart(paramName, new FileBody(((File) paramValue), "application/zip")); 
// For usual String parameters 
entity.addPart(paramName, new StringBody(paramValue.toString(), "text/plain", Charset.forName("UTF-8"))); 
post.setEntity(entity); 
// Here we go! 
String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); 
client.getConnectionManager().shutdown(); 
+0

답장을 보내 주셔서 감사합니다. – qusr

+0

언제든지 환영합니다. –

0

HTTP 요청과 장난의 또 다른 빠른 방법 [까다로운 부분은 MultipartEntity의 사용이다]를 curl를 사용하는 것입니다.

관련 문제