【问题标题】:HttpPost arguments posted to server returns HTTP 500 error发布到服务器的 HttpPost 参数返回 HTTP 500 错误
【发布时间】:2013-12-09 12:01:23
【问题描述】:

我正在尝试将 curl '-F' 选项的等效项发送到指定的 URL。

这是使用 Curl 命令的样子:

curl -F"optionName=cool" -F"file=@myFile" http://myurl.com

我相信我在 Apache httpcomponents 库中使用 HttpPost 类是正确的。

我提供了一个名称=值类型的参数。 optionName 只是一个字符串,“file”是我本地存储在驱动器上的文件(因此 @myFile 表示它是本地文件)。

如果我打印响应,我会收到 HTTP 500 错误...我不确定是什么导致了这里的问题,因为服务器在使用上述 Curl 命令时会做出应有的响应。查看下面的代码时,我犯了一些简单的错误吗?

    HttpPost post = new HttpPost(postUrl);
    HttpClient httpClient = HttpClientBuilder.create().build();

    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair(optionName, "cool"));
    nvps.add(new BasicNameValuePair(file, "@myfile"));

    try {
        post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        HttpResponse response = httpClient.execute(post);
        // do something with response
    } catch (Exception e) {
        e.printStackTrace();
    } 

【问题讨论】:

    标签: java curl apache-httpcomponents


    【解决方案1】:

    尝试使用MultipartEntity 而不是UrlEncodedFormentity,来处理参数和文件上传:

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("optionName", "cool");
    entity.addPart("file", new FileBody("/path/to/your/file"));
    ....
    
    post.setEntity(entity);
    

    编辑

    MultipartEntity 已弃用,FileBody 构造函数采用File,而不是String,所以:

    MultipartEntityBuilder entity = MultipartEntityBuilder.create();
    entity.addTextBody("optionName", "cool");
    entity.addPart("file", new FileBody(new File("/path/to/your/file")));
    ....
    post.setEntity(entity.build());
    

    感谢@CODEBLACK。

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2017-08-26
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多