首頁 > 軟體

Java webservice的POST和GET請求呼叫方式

2022-03-23 13:03:17

webservice的POST和GET請求呼叫

POST請求

1.傳送請求

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傳送SOAP請求
 * @param wsdl url地址
 * @param xml   請求體引數
 * @return
 * @throws Exception
 */
public static String sendHttpPost(String wsdl, String xml) throws Exception{
    int timeout = 10000;
    // HttpClient傳送SOAP請求
    System.out.println("HttpClient 傳送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);
    // 列印請求狀態碼
    System.out.println("status:" + status);
    // 獲取響應體輸入流
    InputStream is = postMethod.getResponseBodyAsStream();
    // 獲取請求結果字串
    return new String(ByteStreams.toByteArray(is));
}
/**
 * HttpURLConnection 傳送SOAP請求
 * @param wsdl url地址
 * @param xml   請求體引數
 * @return
 * @throws Exception
 */
public static String sendURLConnection(String wsdl, String xml) throws Exception{
    int timeout = 10000;
    // HttpURLConnection 傳送SOAP請求
    System.out.println("HttpURLConnection 傳送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);
    //傳送請求
    String s = sendHttpPost(wsdl, xml);
    System.out.println(s);
}

GET請求

/**
* 傳送請求
*/
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();
        //設定輸入輸出,因為預設新建立的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("查詢線上狀態1:"+e.getMessage());
    }
    System.out.println(result);
}

通過webService調第三方提供的介面post與get

需求:第三方提供介面路徑,在自己的專案中進行呼叫

注意點:調不通的時候排除介面本身的問題後,看看自己呼叫路徑是不是正確的,有沒多了或者少了【/】,引數的格式是不是跟介面檔案的一致,再不行,那有可能是編碼或者流處理的問題,我在實際開發中就是因為流處理的問題導致調不通。

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();
            // 建立連線
            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);

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com