HttpClient POST傳參, SpringMVC接受
阿新 • • 發佈:2019-01-07
我們在做Http請求的時候,客戶端會從服務端傳一個複雜的引數,但是,大家知道,用GET請求會出現轉義字元報錯等問題,請求會失敗,這時候我們用POST請求傳引數,注意此方支援時候HTTP和HTTPS兩種協議,在URL上面要標註,我這裡是HTTP協議.
客戶端程式碼一:
import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; //用於進行Https請求的HttpClient public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); } }
客戶端程式碼二
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /* * 利用HttpClient進行post請求的工具類 */ public class HttpClientUtil { public String doPost(String url,Map<String,String> map,String charset){ HttpClient httpClient = null; HttpPost httpPost = null; String result = null; try{ httpClient = new SSLClient(); httpPost = new HttpPost(url); //設定引數 List<NameValuePair> list = new ArrayList<NameValuePair>(); Iterator iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Entry<String,String> elem = (Entry<String, String>) iterator.next(); list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); } if(list.size() > 0){ UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); httpPost.setEntity(entity); } HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ result = EntityUtils.toString(resEntity,charset); } } }catch(Exception ex){ ex.printStackTrace(); } return result; } /**測試程式碼,此處注意請求地址必須要有許可權,我這裡用的shiro攔截,因為要登入,為了避免登入,此處要把
url 放開,如果你的服務端框架沒有任何攔截器(不用登陸),則不需要做放開許可權的操作,關於shiro使用,可以 諮詢我的QQ:243517277 ***/
public static void main(String[] args){
String url = "http://127.0.0.1:8080/dlcgsdzda_web/";
String charset = "utf-8";
HttpClientUtil httpClientUtil = new HttpClientUtil();
String httpOrgCreateTest = url + "redict/test.do";
Map<String,String> createMap = new HashMap<String,String>();
createMap.put("name","左國斌");
createMap.put("pass","admin");
createMap.put("key","@#!`\\\\\\\\");
createMap.put("value","<># [email protected]#%^");
createMap.put("url",httpOrgCreateTest);
String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
System.out.println("result:"+httpOrgCreateTestRtn);
}
}
服務端程式碼,我這裡用到的是springMVC,注意可以用@ModelAttribute接受POST請求的引數
package org.aisino.dlcgsController;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/redict")
public class T {
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> test(HttpServletRequest request,
@ModelAttribute("url")String url,
@ModelAttribute("name")String name,
@ModelAttribute("pass")String pass,
@ModelAttribute("key")String key,
@ModelAttribute("value")String value
) {
Map<String, Object> map=new HashMap<String, Object>();
map.put("url", url);
map.put("name", name);
map.put("pass", pass);
map.put("key", key);
map.put("value", value);
return map;
}
}
注意,httpcilent要依賴httpclient-4.4.jar,我這裡上傳了,這裡還包含了其他用途的jar,例如模仿客戶端檔案上傳的jar,都在其中,大家按選擇挑選.