使用带有参数和文件输入的java URLConnnection对服务器发出POST请求

时间:2015-04-17 08:59:58

标签: java post urlconnection

使用java URLConnnection对服务器发出POST请求
我需要发送一个POST请求,其中包含以下两个参数:

param1=value1
param2=value2

我还需要发送一个文件。

在Apache的情况下,这两个2(发送参数和文件)的事情处理如下

post.setQueryString(queryString)  // queryString is url encoded for eg: param1=value1&param2=value2
post.setRequestEntity(entity)  // entity is constructed using file input stream with corresponding format

如果您有任何与此问题相关的内容,请与我们联系。

请注意:当我尝试使用Google Chrome REST客户端插件时,我收到如下响应(尝试使用所有请求内容类型)

UNSUPPORTED FILE FORMAT: 'multipart/form-data' is not a supported content-type
Response code is 400.

1 个答案:

答案 0 :(得分:1)

Try this API from Apache使用POST方法在内部发送请求。

以下是使用API​​的示例代码

   List<org.apache.http.NameValuePair> list =new ArrayList<org.apache.http.NameValuePair>();
   HttpPost postMethod  =  new HttpPost("http://yoururl/ProjectName"); 
   list.add(new BasicNameValuePair("param1", "param1 Value")) ;
   postMethod.setEntity(new UrlEncodedFormEntity(list));
   HttpClient client = HttpClientBuilder.create().build();
   HttpResponse response =  client.execute(postMethod);
   InputStream is = response.getEntity().getContent();