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
我正在尝试使用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));
}
在上面的代码中,我只能设置StringEntity或FileEntity,但不能同时设置两者,我认为这是获取curl命令功能所需的。
尝试使用StringEntity和FileEntity后,我尝试使用MultipartEntity,但没有运气.. 能否请你提供更多细节,如果可能的话,请提供一个例子..
提前致谢。
答案 0 :(得分:0)
必须按如下方式实例化MultipartEntity:
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE
) ;
这对我有用。
默认情况下,MultipartEntity
使用HttpMultipartMode.STRICT
模式进行实例化,该模式在javadocs中记录为" RFC 822,RFC 2045,符合RFC 2046"
有人可以简要介绍这里提到的RFC,以便明确理解。
非常感谢