java使用http获取 GET请求接口数据代码
一,postman截图:
二,java代码:
package com.cxqy.officialserver.dto.personalsub;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* @Author y
* @Date 2022/6/14 15:16
* @Version 1.0
*/
public class GoodsPa {
private String url;
public GoodsPa(String url) {
this.url = url;
}
public void process() {
String res = HttpClientUtils.get((this.url));
JSONObject object = JSONObject.parseObject(res);
System.out.println("object------->"+object);
//这里因为listDataMap中是数组的形式,所以要转成JSONArray来取
JSONArray listDataMap = (JSONArray)getValue(object,"list");
//取出数组中第一个值里面所需要的key对应的value
System.out.println(getValue(listDataMap.getJSONObject(0),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(0),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(1),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(1),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(2),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(2),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(3),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(3),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(4),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(4),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(5),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(5),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(6),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(6),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(7),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(7),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(8),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(8),"thumb"));
System.out.println(getValue(listDataMap.getJSONObject(9),"title"));
// System.out.println(getValue(listDataMap.getJSONObject(9),"thumb"));
// List<JSONObject> items = (List<JSONObject>)((JSONObject)object.get("list")).get("title");
// for(JSONObject item : items){
// this.urlList.add(item.getString("title"));
// }
}
public static Object getValue(JSONObject json, String key){
if(json ==null){
return null;
}else {
if(json.isEmpty()){
return null;
}else {
return json.get(key);
}
}
}
public static void main(String[] args) {
String url = "https://new.yunpinshop.com/app/ewei_shopv2_api.php?i=2&r=goods.get_list&page=132&comefrom=wxapp&openid=sns_wa_&mid=110454&merchid=&authkey=×tamp=1655188745941";
GoodsPa processor = new GoodsPa(url);
processor.process();
}