ajax请求获取数据Java代码
时间: 2023-04-07 07:01:28 浏览: 120
我可以回答这个问题。以下是一个简单的Java代码示例,用于使用ajax请求获取数据:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class AjaxRequest {
public static void main(String[] args) {
try {
URL url = new URL("http://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;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个代码使用Java的HttpURLConnection类来发送GET请求,并从服务器获取JSON格式的数据。
阅读全文