httpClient的post方法使用form格式数据调用接口

Http使用post调用接口,接口只接受form表单数据格式问题?

这个问题的关键是form表单提交的是数据格式是什么样子的,使用httpClient工具类时Header信息如何写。

会影响解决问题思路的因素:

1、         一致以来都是使用json数据格式调用接口的,form表单是什么格式一时向不起来。

2、         使用form表单数据情况,多是在前台页面使用form表单提交,或使用JavaScript中的FormData对象处理提交。如果是后台httpClient工具接口如何提交

解决思路:

1、先百度看网上怎么说的,找到一个有用的帖子:https://www.cnblogs.com/zhang-can/p/7631262.html 中有一句:

ajax发送的data是个字典,是键值对的形式,在http的post请求过程中,把这种键值对转换成

k1=xxx&k2=xxx这种格式,并且会带上一个请求头:

content-type : application/x-www-form-urlencoded

2、 前台访问后台实际实现也是http协议,那使用谷歌的调试工具,模拟一个form表单提交看看请求header和Form Data的情况:

 

点击“view source”显示的格式:

 

这是我们熟悉的格式。

根据上面的测试,修改httpClient的post工具类:

关键的地方是:post请求的Header设置

httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");

在post中的参数格式为:param1=小明&param2=12

调用时实例:

HttpRequestUtil.post(url地址
        , “param1=小明&param2=12”);

 

测试结果:

返回参数:{"data":{},"code":"0","msg":"处理成功"}

工具类代码:

  1 import org.apache.http.client.config.RequestConfig;
  2 import org.apache.http.client.methods.CloseableHttpResponse;
  3 import org.apache.http.client.methods.HttpGet;
  4 import org.apache.http.client.methods.HttpPost;
  5 import org.apache.http.entity.StringEntity;
  6 import org.apache.http.impl.client.CloseableHttpClient;
  7 import org.apache.http.impl.client.HttpClients;
  8 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  9 
 10 import java.io.BufferedReader;
 11 import java.io.IOException;
 12 import java.io.InputStreamReader;
 13 import java.nio.charset.Charset;
 14 
 15 /**
 16  * Created by guoyanan on 2018/8/7 0007.
 17  * 接口调用工具类
 18  */
 19 public class HttpRequestUtil {
 20     private static CloseableHttpClient httpClient;
 21 
 22     static {
 23         PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
 24         cm.setMaxTotal(100);
 25         cm.setDefaultMaxPerRoute(20);
 26         cm.setDefaultMaxPerRoute(50);
 27         httpClient = HttpClients.custom().setConnectionManager(cm).build();
 28     }
 29 
 30     public static String get(String url) {
 31         CloseableHttpResponse response = null;
 32         BufferedReader in = null;
 33         String result = "";
 34         try {
 35             HttpGet httpGet = new HttpGet(url);
 36             RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
 37             httpGet.setConfig(requestConfig);
 38             httpGet.setConfig(requestConfig);
 39             httpGet.addHeader("Content-type", "application/json; charset=utf-8");
 40             httpGet.setHeader("Accept", "application/json");
 41             response = httpClient.execute(httpGet);
 42             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 43             StringBuffer sb = new StringBuffer("");
 44             String line = "";
 45             String NL = System.getProperty("line.separator");
 46             while ((line = in.readLine()) != null) {
 47                 sb.append(line + NL);
 48             }
 49             in.close();
 50             result = sb.toString();
 51         } catch (IOException e) {
 52             e.printStackTrace();
 53         } finally {
 54             try {
 55                 if (null != response) {
 56                     response.close();
 57                 }
 58             } catch (IOException e) {
 59                 e.printStackTrace();
 60             }
 61         }
 62         return result;
 63     }
 64 
 65     public static String post(String url, String jsonString) {
 66         CloseableHttpResponse response = null;
 67         BufferedReader in = null;
 68         String result = "";
 69         try {
 70             HttpPost httpPost = new HttpPost(url);
 71             RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
 72             httpPost.setConfig(requestConfig);
 73             httpPost.setConfig(requestConfig);
 74             httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
 75             httpPost.setHeader("Accept", "application/json");
 76             httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
 77 
 78             response = httpClient.execute(httpPost);
 79             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
 80             StringBuffer sb = new StringBuffer("");
 81             String line = "";
 82             String NL = System.getProperty("line.separator");
 83             while ((line = in.readLine()) != null) {
 84                 sb.append(line + NL);
 85             }
 86             in.close();
 87             result = sb.toString();
 88         } catch (IOException e) {
 89             e.printStackTrace();
 90         } finally {
 91             try {
 92                 if (null != response) {
 93                     response.close();
 94                 }
 95             } catch (IOException e) {
 96                 e.printStackTrace();
 97             }
 98         }
 99         return result;
100     }
101 
102 }

 

转载于:https://www.cnblogs.com/gynbk/p/9449924.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java使用POST请求调用参数格式form-data的接口可以使用Apache HttpClient库来实现。下面是一个示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; public class FormPostRequestExample { public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api"); File file = new File("file.txt"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("Response status: " + response.getStatusLine()); System.out.println(EntityUtils.toString(responseEntity)); httpClient.close(); } } ``` 在上述代码中,我们创建了一个CloseableHttpClient实例,并构造了一个HttpPost对象来表示我们要访问的API的URL。我们还创建了一个File对象来表示我们要上传的文件。 接下来,我们使用MultipartEntityBuilder类来构造一个包含文件数据的HttpEntity对象。我们将文件数据添加到MultipartEntityBuilder实例中,然后将其构建为HttpEntity实例,并将其设置为HttpPost对象的实体。 最后,我们使用HttpClient实例来执行HttpPost请求,并将响应数据打印到控制台上。 请注意,上述示例代码仅适用于上传文件的情况。如果您需要向API发送其他类型的数据,请根据API文档中提供的信息构造正确的HttpEntity对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值