post接口使用postman的form-data传参用java代码实现调用

接口方只支持formdata方式调用不支持json,代码如下

//form表单提交(form-data方式)
public static String doPostByForm() {
	String strResult = "";
	//获取默认的client实例
	CloseableHttpClient client = HttpClients.createDefault();
	//调用的URL路径
	String url = "http://XXXXX";
	//创建httppost实例
	HttpPost httpPost = new HttpPost(url);
	httpPost.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
	//创建参数队列(键值对列表)
	List<NameValuePair> paramPairs = new ArrayList<>();
	paramPairs.add(new BasicNameValuePair(key1, value1));
    paramPairs.add(new BasicNameValuePair(key2, value2));
	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;
}

你可能感兴趣的:(java,笔记,经验分享)