Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 发布到服务器的HttpPost参数返回HTTP 500错误_Java_Curl_Apache Httpcomponents - Fatal编程技术网

Java 发布到服务器的HttpPost参数返回HTTP 500错误

Java 发布到服务器的HttpPost参数返回HTTP 500错误,java,curl,apache-httpcomponents,Java,Curl,Apache Httpcomponents,我试图将curl'-F'选项的等效项发送到指定的URL 这是使用Curl时命令的外观: curl -F"optionName=cool" -F"file=@myFile" http://myurl.com 我相信我在ApacheHttpComponents库中使用HttpPost类是正确的 我提供了参数的名称=值类型。optionName只是一个字符串,“file”是我存储在本地驱动器上的文件(因此@myFile表示它是本地文件) 如果我打印响应,我会得到一个HTTP 500错误。。。我不确定

我试图将curl'-F'选项的等效项发送到指定的URL

这是使用Curl时命令的外观:

curl -F"optionName=cool" -F"file=@myFile" http://myurl.com
我相信我在ApacheHttpComponents库中使用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();
    } 
HttpPost post=新的HttpPost(postrl);
HttpClient HttpClient=HttpClientBuilder.create().build();
List nvps=new ArrayList();
添加(新的BasicNameValuePair(选项名称,“酷”);
添加(新的BasicNameValuePair(文件“@myfile”);
试一试{
post.setEntity(新的UrlEncodedFormEntity(nvps,“UTF-8”);
HttpResponse response=httpClient.execute(post);
//做些有反应的事情
}捕获(例外e){
e、 printStackTrace();
} 

尝试使用
多端口
而不是
UrlEncodedFormentity
来处理参数和文件上载:

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

post.setEntity(entity);

编辑

MultipartEntity
已被弃用,并且
FileBody
构造函数采用的是
文件
,而不是
字符串
,因此:

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