如何在 Java 中的 GET 请求中设置参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18150818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:49:29  来源:igfitidea点击:

How to set parameters in a GET request in Java

javaandroidget

提问by OddCore

So I want to send a GET request with parameters. But it only seems to have conventions for the url you send the request to. Unlike the POST request, I see no way to pass parameters in it.

所以我想发送一个带参数的GET请求。但它似乎只有您将请求发送到的 url 的约定。与 POST 请求不同,我看不到在其中传递参数的方法。

How I send the GET request now, without parameters (might be wrong):

我现在如何发送 GET 请求,没有参数(可能是错误的):

String url = "http://api.netatmo.net/api/getuser";

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

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

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

            int responseCode = con.getResponseCode();
            Log.v(TAG, ("\nSending 'GET' request to URL : " + url));
            Log.v(TAG, ("Response Code : " + responseCode));

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            Log.v(TAG, (response.toString()));

How I send the POST request with parameters:

我如何发送带有参数的 POST 请求:

String url = "https://api.netatmo.net/oauth2/token";
            URL obj = new URL(url);
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

            //add request header
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "grant_type=password&client_id=myid&client_secret=mysecret&username=myusername&password=mypass";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            Log.v(TAG, "\nSending 'POST' request to URL : " + url);
            Log.v(TAG, "Post parameters : " + urlParameters);
            Log.v(TAG, "Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            Log.v(TAG, response.toString());

            access_token = response.substring(17, 74);
            refresh_token = response.substring(93,150);
            getRequest = "/api/getuser?access_token=" + access_token + " HTTP/1.1";

            Log.v(TAG, access_token);
            Log.v(TAG, refresh_token);
            Log.v(TAG, getRequest);

采纳答案by OddCore

Turns out the url the API provided confused me greatly. I fixed the url and it works now.

结果发现 API 提供的 url 使我非常困惑。我修复了网址,现在可以使用了。

回答by Juned Ahsan

As per the HTTP specification GETsupports only path params or url params and hence you cannot put the params in HTTP request body as you do in POSTrequest.

根据 HTTP 规范GET仅支持路径参数或 url 参数,因此您不能像在请求中那样将参数放在 HTTP 请求正文中POST

As Sotirios mentioned in the comments, technically you can still push params in the GET body, but if the APIs are respecting the specs, they will not provide you a way to do it.

正如 Sotirios 在评论中提到的,从技术上讲,您仍然可以在 GET 主体中推送参数,但是如果 API 遵守规范,它们将不会为您提供这样做的方法。

回答by Frank Olschewski

Have you tried to add the query params to the request java.net.URL?

您是否尝试将查询参数添加到请求 java.net.URL 中?

String url = "http://api.netatmo.net/api/getuser?access_token=" + access_token;
URL obj = new URL(url);

回答by dakami

I was encountering the same problem, trying this:

我遇到了同样的问题,尝试这个:

String bla = "http://api.netatmo.net/api/devicelist?access_token=" + AUTH_TOKEN;
URL url = new URL(bla);

BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

String line = "";
String message = "";

while ((line = reader.readLine()) != null)
{
    message += line;
}

I got an exception that the syntax was not correct. When I changed the syntax (by for example encoding with UTF 8) the API would just return errors (like 404 not found...).

我得到一个语法不正确的异常。当我更改语法(例如使用 UTF 8 编码)时,API 只会返回错误(如 404 not found...)。

I finally got it working using this:

我终于用这个让它工作了:

try
{

        System.out.println("Access Token: " + AUTH_TOKEN);

        String url = "http://api.netatmo.net/api/devicelist";
        String query = "access_token=" + URLEncoder.encode(AUTH_TOKEN, CHARSET);

        URLConnection connection = new URL(url + "?" + query).openConnection();
        connection.setRequestProperty("Accept-Charset", CHARSET);

        InputStream response = connection.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(response));

        String line = "";
        String message = "";

        while ((line = reader.readLine()) != null)
        {
            message += line;
        }

        return message;


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Note: CHARSET = "UTF-8"

注意:CHARSET = "UTF-8"