【问题标题】:cURL emulating by HTTPClient Apache通过 HTTPClient Apache 模拟 cURL
【发布时间】:2013-05-24 13:26:15
【问题描述】:

我正在尝试使用他们的 api 将数据上传到 CrowdFlower,为此我正在编写 JAVA 包装器。我正在使用 HttpClient Apache。

CrowdFlower 给出的 cURL 示例如下:curl -T 'sampledata.xlsx' -H 'Content-Type: application/vnd.ms-excel' https://api.crowdflower.com/v1/jobs/upload.json?key={api_key}

这是我的代码:

public InputStream HTTPmethodPostUpload (String authKey, File file) throws ClientProtocolException, IOException{

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("https://api.crowdflower.com/v1/jobs/upload.json?key="+authKey);

        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbody = new FileBody( file,"application/vnd.ms-excel");
        mpEntity.addPart("sampledata.xlsx", cbody );
        httpPost.setEntity(mpEntity);
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entityResponse = response.getEntity();
        return  entityResponse.getContent(); }

但是它会返回错误并显示以下消息:

{不可接受的格式,Content-Type 必须是 \"formats\" 中列出的格式之一,但您发送的是 \"multipart/form-data; boundary=yTuwTm4hWmnasxIMB9dC-sxdELIGoNJVudjJdCz\"","formats" :["application/vnd.oasis.opendocument.spreadsheet","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-excel","text/csv","text/plain"] }}

我不太了解 Apache HttpClient,所以我不明白我的代码中的问题出在哪里。

【问题讨论】:

    标签: java api curl httpclient crowdflower


    【解决方案1】:

    你在java哪里设置了头文件?

    -H 'Content-Type: application/vnd.ms-excel'
    

    试试下面的:

    mpEntity.setContentType("application/vnd.ms-excel");
    

    【讨论】:

    • 不幸的是 MultipartEntity 类没有这样的方法。
    • API 应该提供对 HTTP HEADER 的备用访问。这就是你需要设置的。我发布的示例是通过 Entity 对象。尝试不同的路由到标题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多