String content="";
try {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection(); //获取连接
httpURLConnection.setRequestMethod("GET"); //设置请求方法为POST, 也可以为GET
httpURLConnection.setDoOutput(true);
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while (br.read() != -1) {
sb.append(br.readLine());
}
content = new String(sb);
content = new String(content.getBytes("GB2312"), "ISO-8859-1");
br.close();
} catch (Exception e) {
throw new Exception("付款接口调用失败!");
try {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection(); //获取连接
httpURLConnection.setRequestMethod("GET"); //设置请求方法为POST, 也可以为GET
httpURLConnection.setDoOutput(true);
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while (br.read() != -1) {
sb.append(br.readLine());
}
content = new String(sb);
content = new String(content.getBytes("GB2312"), "ISO-8859-1");
br.close();
} catch (Exception e) {
throw new Exception("付款接口调用失败!");
}
// 以上为调用的远程接口,数据传输格式为JSON
JSONObject jsonObject = JSONObject.fromObject("{" + content);
String expenseCode = jsonObject.getString("expense_code");
本文详细解析了如何使用Java通过HTTP接口进行数据交互,并解释了JSON格式数据的解析过程。主要内容包括创建URL连接,设置请求方法,获取输入流,读取并解析JSON数据,最终获取特定字段值。此教程适用于理解网络通信和JSON处理的基本原理。
602

被折叠的 条评论
为什么被折叠?



