java如何用标头发送get请求?

时间:2018-03-23 02:38:54

标签: java c# http-headers

大家好我想尝试在带头的java中发送get请求。我正在寻找像conn.addHeader这样的方法("键","值);但我找不到它。我试过" setRequestProperty"方法,但它不起作用..

public void sendGetRequest(String token) throws MalformedURLException, IOException {
    // Make a URL to the web page
    URL url = new URL("http://api.somewebsite.com/api/channels/playback/HLS");

    // Get the input stream through URL Connection
    URLConnection con = url.openConnection();

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Cache-Control", "no-cache");
    con.setRequestProperty("Authorization", "bearer " + token);

    InputStream is = con.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;

    // read each line and write to System.out
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

它返回Httpresponse 401错误。

我的办公室伙伴使用unity c#发送获取请求标头,他的代码看起来像是休息。

  JsonData jsonvale = JsonMapper.ToObject(reqDataGet);
        // Debug.Log(jsonvale["access_token"].ToString());
        // /*
        string url = "http://api.somewebsite.com/api/channels/playback/HLS";
        var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) =>
        {
            switch (req.State)
            {
                case HTTPRequestStates.Finished:
                    if (resp.IsSuccess)
                    {
                    }
                    break;
            }

        });
        request.AddHeader("Cache-Control", "no-cache");
        request.AddHeader("Authorization", "bearer " + jsonvale["access_token"].ToString());
        request.Send();

任何帮助?

1 个答案:

答案 0 :(得分:2)

在Java中我认为你想要这样的东西。

    String url = "http://www.google.com/search?q=stackoverflow";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header
    con.setRequestProperty("User-Agent", "My Example" );

    int responseCode = con.getResponseCode();