Java中HTTPRequest获取数据

发布于 2024-11-06 15:15:47 字数 395 浏览 0 评论 0原文


我想用Java做一个HTTPRequest,然后从服务器获取数据(这不是网页,数据来自数据库)。
我尝试了这个,但 getData 不起作用。
你知道我如何获取数据吗?

  public static void main(String args[]) throws Exception {
    URL url = new URL("http://ip-ad.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    System.out.println("Request method is " + httpCon.getData());
 }

谢谢

I would like to do an HTTPRequest in Java and then get the data from the server (it's not a webpage the data come from a database).
I try this but the getData doesn't work.
Do you know how I can get the Data?

  public static void main(String args[]) throws Exception {
    URL url = new URL("http://ip-ad.com");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    System.out.println("Request method is " + httpCon.getData());
 }

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不语却知心 2024-11-13 15:15:47

您可以将 Web 请求的响应正文作为 获取InputStream with:

httpCon.getInputStream();

从这里开始,这取决于响应数据的格式。如果它是 XML,则将其传递给库来解析 XML。如果您想将其读入String,请参阅:将网站内容读入字符串。这是将其写入本地文件的示例:

InputStream in = httpCon.getInputStream();
OutputStream out = new FileOutputStream("file.dat");
out = new BufferedOutputStream(out);
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
    out.write(buf, 0, len);
}
out.close();

You can get the response body of the web request as an InputStream with:

httpCon.getInputStream();

From there it depends on what the format of the response data is. If it's XML then pass it to a library to parse XML. If you want to read it into a String see: Reading website's contents into string. Here's an example of writing it to a local file:

InputStream in = httpCon.getInputStream();
OutputStream out = new FileOutputStream("file.dat");
out = new BufferedOutputStream(out);
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
    out.write(buf, 0, len);
}
out.close();
稚气少女 2024-11-13 15:15:47

您可以使用 http://jersey.java.net/

这是一个满足您需求的简单库。

You can use http://jersey.java.net/ .

It's a simple lib for your needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文