Java?webservice的POST和GET請求調用方式
更新時間:2022年03月23日 10:40:31 作者:sskai163
這篇文章主要介紹了Java?webservice的POST和GET請求調用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
webservice的POST和GET請求調用
POST請求
1.發(fā)送請求
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請求
?* @param wsdl url地址
?* @param xml ? 請求體參數
?* @return
?* @throws Exception
?*/
public static String sendHttpPost(String wsdl, String xml) throws Exception{
? ? int timeout = 10000;
? ? // HttpClient發(fā)送SOAP請求
? ? System.out.println("HttpClient 發(fā)送SOAP請求");
? ? HttpClient client = new HttpClient();
? ? PostMethod postMethod = new PostMethod(wsdl);
? ? // 設置連接超時
? ? client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
? ? // 設置讀取時間超時
? ? client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
? ? // 然后把Soap請求數據添加到PostMethod中
? ? RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml", "UTF-8");
? ? // 設置請求體
? ? postMethod.setRequestEntity(requestEntity);
? ? int status = client.executeMethod(postMethod);
? ? // 打印請求狀態(tài)碼
? ? System.out.println("status:" + status);
? ? // 獲取響應體輸入流
? ? InputStream is = postMethod.getResponseBodyAsStream();
? ? // 獲取請求結果字符串
? ? return new String(ByteStreams.toByteArray(is));
}
/**
?* HttpURLConnection 發(fā)送SOAP請求
?* @param wsdl url地址
?* @param xml ? 請求體參數
?* @return
?* @throws Exception
?*/
public static String sendURLConnection(String wsdl, String xml) throws Exception{
? ? int timeout = 10000;
? ? // HttpURLConnection 發(fā)送SOAP請求
? ? System.out.println("HttpURLConnection 發(fā)送SOAP請求");
? ? 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();
? ? // 獲取請求結果字符串
? ? 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請求體
/**
?* POST請求體
?* @param map 請求參數
?* @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參數
? ? 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.測試
/**
* HTTP POST請求
*/
public static void main(String[] args) throws Exception{
? ? String wsdl = "http://IP:端口/xxx?wsdl";
? ? String methodName = "方法名";
? ? Map<String ,String> map = new HashMap<>();
? ? map.put("參數名","參數值");
? ? //請求體xml
? ? String xml = getXml(map, methodName);
? ? //發(fā)送請求
? ? String s = sendHttpPost(wsdl, xml);
? ? System.out.println(s);
}GET請求
/**
* 發(fā)送請求
*/
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/方法名?參數名=參數值";
? ? Map result = new HashMap(16);
? ? try {
? ? ? ? URL url = new URL(url);
? ? ? ? HttpURLConnection connection = (HttpURLConnection)url.openConnection();
? ? ? ? //設置輸入輸出,因為默認新創(chuàng)建的connection沒有讀寫權限,
? ? ? ? connection.setDoInput(true);
? ? ? ? connection.setDoOutput(true);
? ? ? ? //接收服務端響應
? ? ? ? int responseCode = connection.getResponseCode();
? ? ? ? if(HttpStatus.SC_OK == responseCode){//表示服務端響應成功
? ? ? ? ? ? InputStream is = connection.getInputStream();
? ? ? ? ? ? //響應結果
? ? ? ? ? ? String s = new String(ByteStreams.toByteArray(is));
? ? ? ? ? ? result = com.alibaba.fastjson.JSONObject.parseObject(s, Map.class);
? ? ? ? }
? ? } catch (Exception e) {
? ? ? ? e.printStackTrace();
? ? ? ? System.out.println("查詢在線狀態(tài)1:"+e.getMessage());
? ? }
? ? System.out.println(result);
}通過webService調第三方提供的接口post與get
需求:第三方提供接口路徑,在自己的項目中進行調用
注意點:調不通的時候排除接口本身的問題后,看看自己調用路徑是不是正確的,有沒多了或者少了【/】,參數的格式是不是跟接口文檔的一致,再不行,那有可能是編碼或者流處理的問題,我在實際開發(fā)中就是因為流處理的問題導致調不通。
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);//請求方式 此處為POST
? ? ? ? ? ? String token= "123456789";//根據實際項目需要,可能需要token值
? ? ? ? ? ? conn.setRequestProperty("token", token);
? ? ? ? ? ? conn.setRequestProperty("Content-type", "application/json");
? ? ? ? ? ? conn.connect();
? ? ? ? ? ? out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");//編碼設置
? ? ? ? ? ? out.write(params);
? ? ? ? ? ? out.flush();
? ? ? ? ? ? out.close();
? ? ? ? ? ? // 獲取響應
? ? ? ? ? ? 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
//根據各自需要返回數組或者字符串 ??
//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);//請求方法 此處為GET
? ? ? ? ? ? conn.setDoInput(true);
? ? ? ? ? ? conn.setDoOutput(true);
? ? ? ? ? ? String token = "123456789";//請求頭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()));//怎么也調不通的時候,有可能流處理有問題
? ? ? ? ? ? ? ? String str = "";
? ? ? ? ? ? ? ? StringBuffer sb = new StringBuffer();
? ? ? ? ? ? ? ? while((str=reader.readLine()) != null){
? ? ? ? ? ? ? ? ? ? sb.append(str);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? //返回字符串的話,就直接返回 sb.toString()
? ? ? ? ? ? ? ? return JSONArray.parseArray(sb.toString());
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println("請求服務失敗,錯誤碼為"+status);
? ? ? ? }catch(Exception e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return null;
? ? }用實體類進行接收返回值的話,需要將返回數據做下轉換,轉成我們需要的實體類格式
//返回數組轉實體類
JSONArray sb = getArray(method,url,params);
if (sb!=null){
? ? List<實體類> list = JSONObject.parseArray(sb.toJSONString(), 實體類.class);
? ? ?return list;
}else {
? ? ?throw new CustomException("調用接口失敗");
}
?
//返回字符串轉實體類
String json = JSONObject.toJSONString(params);
String sb = post(method,url,json);
JSONObject testJson = JSONObject.parseObject(sb);
實體類dto = JSON.toJavaObject(testJson,實體類.class);以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Maven分模塊開發(fā)與依賴管理和聚合和繼承及屬性深入詳細介紹
依賴管理是項目管理中非常重要的一環(huán)。幾乎任何項目開發(fā)的時候需要都需要使用到庫。而這些庫很可能又依賴別的庫,這樣整個項目的依賴形成了一個樹狀結構,而隨著這個依賴的樹的延伸和擴大,一系列問題就會隨之產生2022-10-10
利用java、js或mysql計算高德地圖中兩坐標之間的距離
最近因為工作的需求,需要計算出高德地圖中兩個坐標的距離,通過查找相關資料發(fā)現了多種實現的方法,下面這篇文章主要給大家介紹了關于利用java、js或mysql計算高德地圖中兩坐標之間距離的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。2017-10-10

