【问题标题】:How to set parameters in a GET request in Java如何在 Java 的 GET 请求中设置参数
【发布时间】:2013-08-09 15:53:22
【问题描述】:

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

我现在如何发送 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()));

我如何发送带有参数的 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);

【问题讨论】:

    标签: java android get


    【解决方案1】:

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

    正如 Sotirios 在 cmets 中提到的,从技术上讲,您仍然可以在 GET 正文中推送参数,但如果 API 遵守规范,它们将不会为您提供执行此操作的方法。

    【讨论】:

    • @SotiriosDelimanolis Point 已接受,已编辑答案,请随时进一步编辑。谢谢!
    • 必须有一种方法 - 我正在使用的 API,虽然写得很糟糕 - 清楚地表明有一种方法可以传递参数 - 否则,他们不会使用 GET 方法,因为传递参数是他们想要做的事情
    • @OddCore 您的 API 肯定会提供一种在 URL 中发送 GET 参数的方法,但我不确定它是否提供了一种将它们推送到消息正文中的方法。
    • @JunedAhsan dev.netatmo.com/doc/restapi/getuser 你会认为他们会的,不是吗...
    • 哦,顺便说一句,我想我只需要 url 参数,但是当我尝试它时,我得到了 Malformedurl 异常......
    【解决方案2】:

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

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

    【讨论】:

    • 在 Juned 的回答中查看 cmets
    【解决方案3】:

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

    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;
    }
    

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

    我终于用这个来工作了:

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

    注意:CHARSET = "UTF-8"

    【讨论】:

      【解决方案4】:

      原来 API 提供的 url 让我很困惑。我修复了网址,现在可以使用了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-31
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 2019-02-01
        • 2012-10-03
        相关资源
        最近更新 更多