【问题标题】:HTTPRequest Get Data in JavaJava 中的 HTTPRequest 获取数据
【发布时间】:2011-05-10 07:57:34
【问题描述】:


我想用 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());
 }

谢谢

【问题讨论】:

    标签: java httprequest


    【解决方案1】:

    您可以使用InputStream 获取 Web 请求的响应正文:

    httpCon.getInputStream();
    

    这取决于响应数据的格式。如果是 XML,则将其传递给库以解析 XML。如果您想将其读入String,请参阅:Reading website's contents into 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();
    

    【讨论】:

    • 响应数据以字节为单位。当我执行 getInputStream() 时,我得到了这个答案:请求方法是 sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@83cc67。如果我尝试你没有给出的代码在文件中
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2011-09-04
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多