帮我写一段java调用api接口解析成json格式
时间: 2023-03-28 07:02:54 浏览: 137
从API解析Json
好的,以下是一段Java代码,用于调用API接口并将其解析为JSON格式:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class APICaller {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
JSONObject json = new JSONObject(sb.toString());
System.out.println(json.toString());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,这只是一个示例代码,你需要根据你的具体情况进行修改。
阅读全文