Java HTTP Post表单和文件

时间:2013-11-28 08:35:45

标签: java http-post testfairy

所以我想使用TestFairy API(url:https://app.testfairy.com/api/upload)。此API调用需要3个后参数:

  • api_key(字符串)

  • apk_file(。apk文件)

  • testers_groups(字符串)

到目前为止,我提出了这个问题:

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();

但它不起作用。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分: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类型(但可能不是必需的)。