1、POST請求傳遞參數的方式
2、HttpClient相關包的引用
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
3、工具類的編寫
public static void tsend() { List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("appCode","xxxxxbdd4f7c9bcxxxx")); params.add(new BasicNameValuePair("appKey","xxxxx05A0D2CBxxxx58D")); params.add(new BasicNameValuePair("receiver","1801956xxxx")); params.add(new BasicNameValuePair("content","測試18019563xxx")); String url="http://xx.203.210.xxx:8081/mrsr/rest/mc/sms"; sendPostByUrlEncoder(url,params); }
/** * 描述:POST提交,采用x-www-form-urlencoded 構建參數,即將表單內的數據轉換為鍵值對,如:name=java&age=23 * date: 2021年8月3日 下午2:38:24 * @author wuyechun2010@163.com * @param url * @param map * @return * @since JDK 1.8 */ public static String sendPostByUrlEncoder(String url,Map<String, String> map){ List<NameValuePair> params=new ArrayList<NameValuePair>(); for(Map.Entry<String, String> entry : map.entrySet()){ params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); HttpResponse response = null; try { httppost.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); HttpClient httpClient =HttpClientBuilder.create().build(); response = httpClient.execute(httppost); } catch (IOException e) { e.printStackTrace(); } HttpEntity httpEntity = response.getEntity(); String result = null; try { result = EntityUtils.toString(httpEntity); } catch (Exception e) { e.printStackTrace(); } System.out.println("輸出參數為:"+result); return result; }
4、測試調用
public static void tsend() { List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("appCode","7b9272df9cbxxxx7c9bc222350")); params.add(new BasicNameValuePair("appKey","1CKBMT3QA0xxxxxB3B00002EF9D58D")); params.add(new BasicNameValuePair("receiver","1801956xxxx")); params.add(new BasicNameValuePair("content","測試18019563xxx")); String url="http://5x.2x3.xxx.160:8081/mrsr/rest/mc/sms"; sendPostByUrlEncoder(url,params); }