java实现:
/**
* form表单提交
* @param url
* @param map
* @return
*/
public static String doPostForm(String url, Map<String, Object> map) {
String strResult = "";
// 1. 获取默认的client实例
CloseableHttpClient client = HttpClients.createDefault();
// 2. 创建httppost实例
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// 3. 创建参数队列(键值对列表)
List<NameValuePair> paramPairs = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
Object val = map.get(key);
paramPairs.add(new BasicNameValuePair(key, val.toString()));
}
UrlEncodedFormEntity entity;
try {
// 4. 将参数设置到entity对象中
entity = new UrlEncodedFormEntity(paramPairs, "UTF-8");
System.out.println("封装的参数:"+entity);
// 5. 将entity对象设置到httppost对象中
httpPost.setEntity(entity);
// 6. 发送请求并回去响应
CloseableHttpResponse resp = client.execute(httpPost);
try {
// 7. 获取响应entity
HttpEntity respEntity = resp.getEntity();
strResult = EntityUtils.toString(respEntity, "UTF-8");
} finally {
// 9. 关闭响应对象
resp.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 10. 关闭连接,释放资源
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return strResult;
}
第二种方式:文章来源:https://www.toymoban.com/news/detail-525945.html
导入依赖:文章来源地址https://www.toymoban.com/news/detail-525945.html
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.8</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
/**
* @param params 非文件参数
* @param url 请求地址
* @param header 请求头信息(没有传null)
* @return String
**/
public static String sendPostRequest(String url, Map<String, Object> params, Map<String, String> header) {
try {
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type", AppConsts.CONTENT_TYPE_FORM + ";charset=" + AppConsts.ENCODING_UTF8);
if (!CollectionUtils.isEmpty(header)){
header.forEach(postMethod::setRequestHeader);
}
NameValuePair[] data = new NameValuePair[params.size()];
int i = 0;
for (String key : params.keySet()) {
data[i] = new NameValuePair(key, params.get(key) == null ? "" : params.get(key).toString());
i++;
}
postMethod.setRequestBody(data);
HttpClient httpClient = new HttpClient();
int response = httpClient.executeMethod(postMethod); // 执行POST方法
String result = postMethod.getResponseBodyAsString();
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
到了这里,关于postman form-data传参java实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!