简体   繁体   English

HttpUrlConnection“ PUT”请求也发送“ GET”请求

[英]HttpUrlConnection “PUT” Request also sends “GET” Request

My issue is that when I use HttpURLConnection to send a PUT request to my REST API , it sends a GET request first, then a PUT request. 我的问题是,当我使用HttpURLConnectionPUT请求发送到REST API ,它将首先发送GET请求,然后发送PUT请求。 I was wondering if any of my code I have to send a PUT request is causing it to also send a GET request. 我想知道我必须发送PUT请求的任何代码是否导致它也发送GET请求。

I know that this issue occurs in my Android code because I also use Postman to send PUT requests, and I never have an issue. 我知道在我的Android代码中会发生此问题,因为我也使用Postman发送PUT请求,而我从来没有遇到过问题。

Below is a copy of the function I use to send HttpUrlConnection requests. 下面是我用来发送HttpUrlConnection请求的函数的副本。

public String HTTPConnection(String requestType, String url, String input, Context context, Activity activity){
        HttpURLConnection connection = null;
        try {
            URL OBJ = new URL(url);
            connection = (HttpURLConnection) OBJ.openConnection();
            connection.setRequestMethod(requestType);
            switch (requestType.toLowerCase()) {
                case "get":
                    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    int i = 1;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                        i++;
                    }
                    in.close();
                    return response.toString();
                case "put":
                    if (!input.equals("")){
                        OBJ.openStream();
                        connection.setRequestProperty("Content-type", "application/json");
                        connection.setRequestProperty("Accept", "application/json");
                        connection.setDoOutput(true);
                    }
                    Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                    writer.write(input);
                    writer.flush();
                    writer.close();
                    connection.getInputStream();
                    return "";
                default:
                    return "";
            }
        } catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }

OBJ.openStream(); sends a GET request (see java.net.URL.openStream ), since it opens an input stream for reading the contents of that URL. 发送GET请求(请参阅java.net.URL.openStream ),因为它打开了一个输入流以读取该URL的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM