- 在本地IDE编写Java代码访问url,并返回json字符串
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DataJson {
public static String request(String httpUrl, String httpArg) {
String username = "xxxxxx";
String psd = "xxxxxx";
String requestURL = "http://localhost:xxxx/xxx/xxx/xxx/x/xx/xxx";
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url = new URL(httpUrl);
String encoding = new String(Base64.encode(new String(username+":"+psd).getBytes()));
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty( "Authorization","Basic "+encoding);
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
/**
* @param urlAll
* :请求接口
* @param httpArg
* :参数
* @return 返回结果
*/
String httpUrl = "http://localhost:xxxx/xxx/xxx/xxx/x/xx/xxx";
String httpArg="";
System.out.println(request(httpUrl,httpArg));
}
}
- 对返回的JSON Object对象进行解析,获取你想要的数据。解析我这里使用的是alibaba的fastjson API。相关jar包下载地址:https://mvnrepository.com/
JSONObject propertiesObject = JSONObject.parseObject(json).get("name");
System.out.println(propertiesObject.get("name1"));
System.out.println(propertiesObject.get("name2"));
JSON解析一定要掌握两条规则: