http協定的接口一般會有GET請求和POST請求兩種,下面總結一下自己常用到的幾種調用方式:
第一種:WebClient發送GET請求
import net.sf.json.JSONObject;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.Test;
@Test
public void getResponse() {
String url = "http://ip:port/test";
//建立連接配接
WebClient wc = WebClient.create(url);
//擷取服務端傳回的json
String str = wc.accept("application/json").get(String.class);
System.out.println(str);
//根據傳回的資料格式自己,組裝資料。這裡假設傳回的資料格式為
//{"status":,"data":[{"name":"youyou"},{"name":"test"}]},将json轉為對象
JSONObject JsonObject =JSONObject.fromObject(str);
System.out.println(JsonObject.get("status")); //4000
}
第二種:WebClient發送POST請求
與get方式類似,需調用WebClient的post方法即可,這裡暫時略,有問題的再寫。
PS:最近本人正在組建自己的技術交流群,有興趣的朋友可以加群。
群号:198450184(Lea項目組)