Java 中的 HTTP GET 请求 [英] HTTP GET request in java

查看:43
本文介绍了Java 中的 HTTP GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 java 上使用 http get 请求到端口号 4567 上的本地主机.我收到了获取请求:wget -q -O- http://localhost:4567/XXXX"[XXXX 是一些参数 - 不相关].我找到了一个 java 库 java.net.URLConnection 来处理这些事情,但似乎 URLConnection 对象应该接收 url/port/.. 和所有其他类型的参数(换句话说,你必须构造对象自己),但是,正如我上面写的那样,我得到了完整的 http get 请求.有没有一种方法可以简单地拍摄"请求而不处理为 URLConnection 构建字段?

I'm trying to use http get request on java, to my localhost on port number 4567. I got the get request: "wget -q -O- http://localhost:4567/XXXX" [XXXX is some parameter - not relevent]. I've found a java library java.net.URLConnection for these kind of things but it seems that the URLConnection object is supposed to receive the url/port/.. and all other kind of parameters (In other words, you have to construct the object yourself), however, I got the full http get request as I've written above. Is there a way to simply 'shoot' the request without dealing with constructing the field for URLConnection?

推荐答案

您可以使用您的 URL 创建 URL 对象,它会自己找出端口和其他东西.参考:https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

You can create the URL object using your URL, it will figure out ports and other things itself. Ref : https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://localhost:4567/XXXX");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

这篇关于Java 中的 HTTP GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆