2012-11-20 176 views
1
curl -F [email protected]/path/to/index.html -u [email protected] -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps 

我想要使用一个使用HttpClient库的java程序实现相同的功能。使用java的cURL命令

DefaultHttpClient client = new DefaultHttpClient(); 
HttpHost targetHost = new HttpHost("build.phonegap.com", 443, "https"); 
client.getCredentialsProvider().setCredentials( 
new AuthScope(targetHost.getHostName(), targetHost.getPort(),AuthScope.ANY_REALM), 
new UsernamePasswordCredentials("[email protected]", "abc123")); 

String authToken = "?auth_token=abcdefgh"; 

HttpPost httpPost = new HttpPost("https://build.phonegap.com/api/v1/apps" + authToken); 

String jsonString = "{\"title\":\"API V1 App\",\"create_method\":\"file\"}"; 
MultipartEntity multipartEntity = new MultipartEntity(); 
multipartEntity.addPart(new FormBodyPart("data", new StringBody(jsonString))); 
multipartEntity.addPart("file", new FileBody(new File("C:/Users/Desktop/app.zip"))); 

/*StringEntity entity = new StringEntity(jsonString, "UTF-8"); */ 
httpPost.setEntity(multipartEntity); 

System.out.println("executing request " + httpPost.getRequestLine()); 
HttpResponse httpResponse = client.execute(httpPost); 
HttpEntity entity = httpResponse.getEntity(); 
System.out.println(httpResponse.getStatusLine()); 
if(entity != null){ 
System.out.println(EntityUtils.toString(entity)); 
} 

在上面的代码中,我只能设置StringEntity或FileEntity但不同时,我认为这是什么是需要得到curl命令的功能。

与StringEntity和FileEntity努力之后,我试着用MultipartEntity,但没有运气.. 能否请您为我提供更多的细节,如果可能的例子..

在此先感谢。

回答

0

一个人来实例化MultipartEntity如下:

MultipartEntity multipartEntity = new MultipartEntity(
             HttpMultipartMode.BROWSER_COMPATIBLE 
                 ) ; 

这为我工作。

默认情况下,MultipartEntity实例化为HttpMultipartMode.STRICT模式,在javadoc中记录为“RFC 822,RFC 2045,RFC 2046兼容”。

可有人介绍了RFC这里清楚的认识提到的..

非常感谢