標籤:efault ash dia return 提交 params void sch turn
方法一: HttpClient
public void postTest(HttpServletRequest request,Integer type,String phone,String passwd,String schoolld,String agent){ String url = "xxxxxxxxx";//發送請求的URL地址 JSONObject jsonObject = new JSONObject();//封裝參數 jsonObject.put("phone", "xxxx"); jsonObject.put("agent", "xxxx"); String params=jsonObject.toString(); sendPostHttpClient(url, params);} public String sendPostHttpClient(String url, String data) { String response = null; try { CloseableHttpClient httpclient = null; CloseableHttpResponse httpresponse = null; try { httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); //StringEntity stringentity = new StringEntity(data, ContentType.create("text/json", "UTF-8"));參數傳遞文字格式設定 StringEntity stringentity = new StringEntity(data, ContentType.create("application/json", "UTF-8"));//參數傳遞json格式 httppost.setEntity(stringentity); httpresponse = httpclient.execute(httppost); response = EntityUtils.toString(httpresponse.getEntity()); logger.info("response: " + response); } finally { if (httpclient != null) { httpclient.close(); } if (httpresponse != null) { httpresponse.close(); } } } catch (Exception e) { e.printStackTrace(); } return response;}
方法二:RestTemplate
public Map<String,String> getShangHaiCarDealCount(String formatTime) { Map<String,String> map=new HashMap<>(); map.put("flag", "fail"); String cycle = "1"; String pic_type = "3"; String qsrq = formatTime; String Submit = "顯示"; String zzrq = formatTime; String result = null; try { String url = "http://xxxxxxxxxxxxxxxxxxxxxx"; RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); // 請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 封裝參數,千萬不要替換為Map與HashMap,否則參數無法傳遞 MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>(); // 也支援中文 params.add("cycle", cycle); params.add("pic_type", pic_type); params.add("qsrq", qsrq); params.add("Submit", Submit); params.add("zzrq", zzrq); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers); // 執行HTTP請求 ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class); result = response.getBody(); map.put("result", result); map.put("flag", "success"); } catch (Exception e) { e.printStackTrace(); } return map; }
java 類比發送post請求測試