2013-11-28 36 views
0

所以我想使用TestFairy API(url:https://app.testfairy.com/api/upload)。这个API调用预计3个后paramters:Java HTTP Post form and file

  • api_key(串)

  • apk_file(.apk文件)

  • testers_groups(串)

到目前为止,我来了up with this:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 

List <NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("testers_groups", testers)); 
params.add(new BasicNameValuePair("api_key", key)); 

httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 

MultipartEntity reqEntity = new MultipartEntity(); 
reqEntity.addPart("apk_file", new FileBody(file)); 

httppost.setEntity(reqEntity); 

System.out.println("executing request " + httppost.getRequestLine()); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity resEntity = response.getEntity(); 

System.out.println(response.getStatusLine()); 
if (resEntity != null) { 
    System.out.println(EntityUtils.toString(resEntity)); 
} 
if (resEntity != null) { 
    resEntity.consumeContent(); 
} 

httpclient.getConnectionManager().shutdown(); 

但它不起作用。

任何人都可以指向正确的方向吗?

回答

0

尝试这样:

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
entity.addPart("api_key", new StringBody(key)); 
entity.addPart("apk_file", new FileBody(file)); 
entity.addPart("testers_groups", new StringBody(testers)); 
HttpPost httpPost = new HttpPost(url); 
httpPost.setEntity(entity); 

HttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(httpPost); 

可选在StringBodyFileBody构造函数添加MIME类型(但可能不是必要的)。