post接口使用postman的form-data传参用java代码实现调用_java post form-data
接口方只支持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. 获取响应entityHttpEntity 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;}