如何使用HttpPost表示curl命令:curl --form" tag = mytag" --form" archive=@test.pdf; type = application / pdf"

时间:2014-06-23 14:28:59

标签: java json http curl http-post

如何使用HttpPost表示curl命令:

curl --form "tag=mytag"  --form "archive=@c:/etc/test.pdf;type=application/pdf" ...

以下是我的代码:

HttpPost httpPost = new HttpPost(www.resourceURL.com);
httpPost.setHeader(Authorization: bearer cb084803-ba48-xxxx-xxxx-2a275e199c38)
....

下面是我完成的代码: 但我收到HTTP 500错误

    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    HttpPost httpPost = new HttpPost(resourceURL);
    httpPost.setHeader(OAuthConstants.AUTHORIZATION, bearer cb084803-ba48-xxx-xxx-2a275xxx99c38 ));
    httpPost.setHeader(OAuthConstants.CONTENTE_TYPE, OAuthConstants.ENCODED_CONTENT_DATA);
    httpPost.setHeader(OAuthConstants.PARTNERUSERID, login);
    //------------------------------------------------------------------------
    parameters.add(new BasicNameValuePair("title", doc.getTitre()));
    parameters.add(new BasicNameValuePair("tag", doc.getTag()));
    parameters.add(new BasicNameValuePair("archive", "@" + doc.getPath() + ";type=application/pdf"));
    httpPost.setEntity(new UrlEncodedFormEntity(parameters));
    //------------------------------------------------------------------------
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = null;
        response = httpClient.execute(httpPost);
        code = response.getStatusLine().getStatusCode();

我不知道如何解决这个问题

我检查内容响应的背景,我有这个结果:

[{"error":"bad_request","error_description":"malformed Json : Expected BEGIN_OBJECT but was STRING at line 1 column 1"}]

1 个答案:

答案 0 :(得分:0)

创建UrlEncodedFormEntity并在那里添加表单元素

List<NameValuePair> formEntries = new ArrayList<>(); // or whatever List sub-type
formEntries.add(new BasicNameValuePair("tag", "my-tag"));
// more
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formEntries);
httpPost.setEntity(entity);