Java?webservice的POST和GET請(qǐng)求調(diào)用方式
webservice的POST和GET請(qǐng)求調(diào)用
POST請(qǐng)求
1.發(fā)送請(qǐng)求
import java.io.DataOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import com.google.common.io.ByteStreams; /** ?* HttpClient發(fā)送SOAP請(qǐng)求 ?* @param wsdl url地址 ?* @param xml ? 請(qǐng)求體參數(shù) ?* @return ?* @throws Exception ?*/ public static String sendHttpPost(String wsdl, String xml) throws Exception{ ? ? int timeout = 10000; ? ? // HttpClient發(fā)送SOAP請(qǐng)求 ? ? System.out.println("HttpClient 發(fā)送SOAP請(qǐng)求"); ? ? HttpClient client = new HttpClient(); ? ? PostMethod postMethod = new PostMethod(wsdl); ? ? // 設(shè)置連接超時(shí) ? ? client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); ? ? // 設(shè)置讀取時(shí)間超時(shí) ? ? client.getHttpConnectionManager().getParams().setSoTimeout(timeout); ? ? // 然后把Soap請(qǐng)求數(shù)據(jù)添加到PostMethod中 ? ? RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml", "UTF-8"); ? ? // 設(shè)置請(qǐng)求體 ? ? postMethod.setRequestEntity(requestEntity); ? ? int status = client.executeMethod(postMethod); ? ? // 打印請(qǐng)求狀態(tài)碼 ? ? System.out.println("status:" + status); ? ? // 獲取響應(yīng)體輸入流 ? ? InputStream is = postMethod.getResponseBodyAsStream(); ? ? // 獲取請(qǐng)求結(jié)果字符串 ? ? return new String(ByteStreams.toByteArray(is)); } /** ?* HttpURLConnection 發(fā)送SOAP請(qǐng)求 ?* @param wsdl url地址 ?* @param xml ? 請(qǐng)求體參數(shù) ?* @return ?* @throws Exception ?*/ public static String sendURLConnection(String wsdl, String xml) throws Exception{ ? ? int timeout = 10000; ? ? // HttpURLConnection 發(fā)送SOAP請(qǐng)求 ? ? System.out.println("HttpURLConnection 發(fā)送SOAP請(qǐng)求"); ? ? URL url = new URL(wsdl); ? ? HttpURLConnection conn = (HttpURLConnection) url.openConnection(); ? ? conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); ? ? conn.setRequestMethod("POST"); ? ? conn.setUseCaches(false); ? ? conn.setDoInput(true); ? ? conn.setDoOutput(true); ? ? conn.setConnectTimeout(timeout); ? ? conn.setReadTimeout(timeout); ? ? DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); ? ? dos.write(xml.getBytes("utf-8")); ? ? dos.flush(); ? ? InputStream inputStream = conn.getInputStream(); ? ? // 獲取請(qǐng)求結(jié)果字符串 ? ? return new String(ByteStreams.toByteArray(inputStream)); }
ByteStreams的maven
<dependency> ? ? ? ? <groupId>com.google.guava</groupId> ? ? ? ? <artifactId>guava</artifactId> ? ? ? ? <version>27.0.1-jre</version> ? ? </dependency>
2.POST請(qǐng)求體
/** ?* POST請(qǐng)求體 ?* @param map 請(qǐng)求參數(shù) ?* @param methodName 方法名 ?* @return ?*/ public static String getXml(Map<String ,String> map , String methodName){ ? ? StringBuffer sb = new StringBuffer(""); ? ? sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); ? ? sb.append("<soap:Envelope " ? ? ? ? ? ? + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " ? ? ? ? ? ? + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' " ? ? ? ? ? ? + "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"); ? ? sb.append("<soap:Body>"); ? ? sb.append("<" + methodName + " xmlns='http://tempuri.org/'>"); ? ? //post參數(shù) ? ? for (String str : map.keySet()){ ? ? ? ? sb.append("<"+str+">"+map.get(str)+"</"+str+">"); ? ? } ? ? sb.append("</" + methodName + ">"); ? ? sb.append("</soap:Body>"); ? ? sb.append("</soap:Envelope>"); ? ? return sb.toString(); }
3.測(cè)試
/** * HTTP POST請(qǐng)求 */ public static void main(String[] args) throws Exception{ ? ? String wsdl = "http://IP:端口/xxx?wsdl"; ? ? String methodName = "方法名"; ? ? Map<String ,String> map = new HashMap<>(); ? ? map.put("參數(shù)名","參數(shù)值"); ? ? //請(qǐng)求體xml ? ? String xml = getXml(map, methodName); ? ? //發(fā)送請(qǐng)求 ? ? String s = sendHttpPost(wsdl, xml); ? ? System.out.println(s); }
GET請(qǐng)求
/** * 發(fā)送請(qǐng)求 */ import com.google.common.io.ByteStreams; import org.apache.commons.httpclient.HttpStatus; import org.codehaus.jettison.json.JSONObject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public static void main(String[] args) throws Exception{ ?? ?String url = "http://IP:端口/xxx/方法名?參數(shù)名=參數(shù)值"; ? ? Map result = new HashMap(16); ? ? try { ? ? ? ? URL url = new URL(url); ? ? ? ? HttpURLConnection connection = (HttpURLConnection)url.openConnection(); ? ? ? ? //設(shè)置輸入輸出,因?yàn)槟J(rèn)新創(chuàng)建的connection沒有讀寫權(quán)限, ? ? ? ? connection.setDoInput(true); ? ? ? ? connection.setDoOutput(true); ? ? ? ? //接收服務(wù)端響應(yīng) ? ? ? ? int responseCode = connection.getResponseCode(); ? ? ? ? if(HttpStatus.SC_OK == responseCode){//表示服務(wù)端響應(yīng)成功 ? ? ? ? ? ? InputStream is = connection.getInputStream(); ? ? ? ? ? ? //響應(yīng)結(jié)果 ? ? ? ? ? ? String s = new String(ByteStreams.toByteArray(is)); ? ? ? ? ? ? result = com.alibaba.fastjson.JSONObject.parseObject(s, Map.class); ? ? ? ? } ? ? } catch (Exception e) { ? ? ? ? e.printStackTrace(); ? ? ? ? System.out.println("查詢?cè)诰€狀態(tài)1:"+e.getMessage()); ? ? } ? ? System.out.println(result); }
通過webService調(diào)第三方提供的接口post與get
需求:第三方提供接口路徑,在自己的項(xiàng)目中進(jìn)行調(diào)用
注意點(diǎn):調(diào)不通的時(shí)候排除接口本身的問題后,看看自己調(diào)用路徑是不是正確的,有沒多了或者少了【/】,參數(shù)的格式是不是跟接口文檔的一致,再不行,那有可能是編碼或者流處理的問題,我在實(shí)際開發(fā)中就是因?yàn)榱魈幚淼膯栴}導(dǎo)致調(diào)不通。
POST
? ? public static String post(String method,String urls,String params){ ? ? ? ? OutputStreamWriter out = null; ? ? ? ? try ? ? ? ? { ? ? ? ? ? ? URL url = new URL(urls);//第三方接口路徑 ? ? ? ? ? ? HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); ? ? ? ? ? ? // 創(chuàng)建連接 ? ? ? ? ? ? conn.setDoOutput(true); ? ? ? ? ? ? conn.setDoInput(true); ? ? ? ? ? ? conn.setUseCaches(false); ? ? ? ? ? ? conn.setRequestMethod(method);//請(qǐng)求方式 此處為POST ? ? ? ? ? ? String token= "123456789";//根據(jù)實(shí)際項(xiàng)目需要,可能需要token值 ? ? ? ? ? ? conn.setRequestProperty("token", token); ? ? ? ? ? ? conn.setRequestProperty("Content-type", "application/json"); ? ? ? ? ? ? conn.connect(); ? ? ? ? ? ? out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//編碼設(shè)置 ? ? ? ? ? ? out.write(params); ? ? ? ? ? ? out.flush(); ? ? ? ? ? ? out.close(); ? ? ? ? ? ? // 獲取響應(yīng) ? ? ? ? ? ? BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); ? ? ? ? ? ? String lines; ? ? ? ? ? ? StringBuffer sb = new StringBuffer(); ? ? ? ? ? ? while ((lines = reader.readLine()) != null ){ ? ? ? ? ? ? ? ? lines = new String(lines.getBytes(), "utf-8" ); ? ? ? ? ? ? ? ? sb.append(lines); ? ? ? ? ? ? } ? ? ? ? ? ? reader.close(); ? ? ? ? ? ? System.out.println(sb); ? ? ? ? ? ? return sb.toString(); ? ? ? ? ? ? ? ? }catch(Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? return null; ? ? }
GET
//根據(jù)各自需要返回?cái)?shù)組或者字符串 ?? //public static String getObject(String method,String urls,String params){ ?public static JSONArray getArray(String method,String urls,String params){ ? ? ? ? OutputStreamWriter out = null; ? ? ? ? try{ ? ? ? ? ? ? URL url = new URL(urls);//接口路徑 ? ? ? ? ? ? HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); ? ? ? ? ? ? conn.setRequestMethod(method);//請(qǐng)求方法 此處為GET ? ? ? ? ? ? conn.setDoInput(true); ? ? ? ? ? ? conn.setDoOutput(true); ? ? ? ? ? ? String token = "123456789";//請(qǐng)求頭token ? ? ? ? ? ? conn.setRequestProperty("token",token); ? ? ? ? ? ? conn.connect(); ? ? ? ? ? ? int status = conn.getResponseCode(); ? ? ? ? ? ? System.out.println(status); ? ? ? ? ? ? ? if(status == 200){ ? ? ? ? ? ? ? ? BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));//怎么也調(diào)不通的時(shí)候,有可能流處理有問題 ? ? ? ? ? ? ? ? String str = ""; ? ? ? ? ? ? ? ? StringBuffer sb = new StringBuffer(); ? ? ? ? ? ? ? ? while((str=reader.readLine()) != null){ ? ? ? ? ? ? ? ? ? ? sb.append(str); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? //返回字符串的話,就直接返回 sb.toString() ? ? ? ? ? ? ? ? return JSONArray.parseArray(sb.toString()); ? ? ? ? ? ? } ? ? ? ? ? ? System.out.println("請(qǐng)求服務(wù)失敗,錯(cuò)誤碼為"+status); ? ? ? ? }catch(Exception e){ ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? ? ? return null; ? ? }
用實(shí)體類進(jìn)行接收返回值的話,需要將返回?cái)?shù)據(jù)做下轉(zhuǎn)換,轉(zhuǎn)成我們需要的實(shí)體類格式
//返回?cái)?shù)組轉(zhuǎn)實(shí)體類 JSONArray sb = getArray(method,url,params); if (sb!=null){ ? ? List<實(shí)體類> list = JSONObject.parseArray(sb.toJSONString(), 實(shí)體類.class); ? ? ?return list; }else { ? ? ?throw new CustomException("調(diào)用接口失敗"); } ? //返回字符串轉(zhuǎn)實(shí)體類 String json = JSONObject.toJSONString(params); String sb = post(method,url,json); JSONObject testJson = JSONObject.parseObject(sb); 實(shí)體類dto = JSON.toJavaObject(testJson,實(shí)體類.class);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Maven分模塊開發(fā)與依賴管理和聚合和繼承及屬性深入詳細(xì)介紹
依賴管理是項(xiàng)目管理中非常重要的一環(huán)。幾乎任何項(xiàng)目開發(fā)的時(shí)候需要都需要使用到庫。而這些庫很可能又依賴別的庫,這樣整個(gè)項(xiàng)目的依賴形成了一個(gè)樹狀結(jié)構(gòu),而隨著這個(gè)依賴的樹的延伸和擴(kuò)大,一系列問題就會(huì)隨之產(chǎn)生2022-10-10k8s部署java項(xiàng)目的實(shí)現(xiàn)
本文主要介紹了k8s部署java項(xiàng)目的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12JSP頁面?zhèn)鲄⒊霈F(xiàn)中文亂碼的解決方案
這篇文章主要介紹了JSP頁面?zhèn)鲄⒊霈F(xiàn)中文亂碼的解決方案,非常實(shí)用,需要的朋友可以參考下2014-08-08Java加密 消息摘要算法MAC實(shí)現(xiàn)詳解
這篇文章主要介紹了Java 消息摘要算法MAC實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07利用java、js或mysql計(jì)算高德地圖中兩坐標(biāo)之間的距離
最近因?yàn)楣ぷ鞯男枨?,需要?jì)算出高德地圖中兩個(gè)坐標(biāo)的距離,通過查找相關(guān)資料發(fā)現(xiàn)了多種實(shí)現(xiàn)的方法,下面這篇文章主要給大家介紹了關(guān)于利用java、js或mysql計(jì)算高德地圖中兩坐標(biāo)之間距離的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-10-10