post 两种方式 application/x-www-form-urlencoded和multipart/form-data

本次主要涉及 application/x-www-form-urlencoded方式。

postman访问方式如图:

 

 

 

 

 

java代码实现:

首先使用maven作为第三方依赖管理:

  

 1    <dependencies>
 2         <dependency>
 3             <groupId>com.alibaba</groupId>
 4             <artifactId>fastjson</artifactId>
 5             <version>1.2.57</version>
 6         </dependency>
 7         <dependency>
 8             <groupId>commons-httpclient</groupId>
 9             <artifactId>commons-httpclient</artifactId>
10             <version>3.1</version>
11         </dependency>
12     </dependencies>

 

实现的方法块:

 1  public static FullText fullTextSearch(String token, HashMap<String, String> bodyMap) {
 2         headers.put("token", token);
 3 
 4         try {
 5             PostMethod postMethod = new PostMethod(api);   //api为访问的url
 6 
 7             for (Map.Entry<String, String> header : headers.entrySet()) {
 8                 postMethod.setRequestHeader(header.getKey(), header.getValue());
 9             }
10 
11             int size = bodyMap.size();
12             int index = 0;
13             NameValuePair[]  body = new NameValuePair[size];
14             for (Map.Entry<String, String> bodyItem : bodyMap.entrySet()) {
15                 body[index++] = new NameValuePair(bodyItem.getKey(), bodyItem.getValue());
16             }
17             postMethod.setRequestBody(body);
18 
19             HttpClient httpClient = new HttpClient();
20             int response = httpClient.executeMethod(postMethod); // 执行POST方法 正常返回200
21             String result = postMethod.getResponseBodyAsString();
22             FullText fullText = JSON.parseObject(result, FullText.class);
23 
24             return fullText;
25         } catch (Exception e) {
26             throw new RuntimeException(e.getMessage());
27         }
28     }

 

posted @ 2019-09-26 08:57  _Meditation  阅读(3370)  评论(0编辑  收藏  举报