[英]cURL command using java
curl -F file=@/path/to/index.html -u lslkdfmkls@gmail.com -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps
I am trying to achieve the same using a java program using HttpClient library. 我正在尝试使用使用HttpClient库的Java程序来实现相同的目的。
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("abc@gmail.com", "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));
}
In the above code I can only set StringEntity or FileEntity but not both and I think this is what is required to get the functionality of the curl command. 在上面的代码中,我只能设置StringEntity或FileEntity,而不能同时设置两者,并且我认为这是获得curl命令功能所必需的。
After trying with StringEntity and FileEntity I tried with MultipartEntity but no luck.. Can you please provide me with more details and if possible an example.. 在尝试了StringEntity和FileEntity之后,我尝试了MultipartEntity,但是没有运气。.能否请您提供更多详细信息,并在可能的情况下提供示例。
Thanks in advance. 提前致谢。
One has to instantiate the MultipartEntity as follows: 必须实例化MultipartEntity,如下所示:
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE
) ;
This worked for me. 这对我有用。
By default the MultipartEntity
is instantiated with HttpMultipartMode.STRICT
mode which is documented in the javadocs as "RFC 822, RFC 2045, RFC 2046 compliant" . 默认情况下, MultipartEntity
用HttpMultipartMode.STRICT
模式实例化, HttpMultipartMode.STRICT
模式在javadocs中记录为“符合RFC 822,RFC 2045和RFC 2046”。
Can someone brief out the RFC's mentioned here for clear understanding.. 有人可以简要介绍这里提到的RFC,以使他们清楚地了解..
Thanks a Lot 非常感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.