错误405-在java http函数调用中找不到方法

n3h0vuf2  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(267)

需要这段代码的帮助。“post”方法很有效。但当我为另一个接受get方法的api将其改为“get”时,它遇到了405错误。
p/s:我已经使用postman测试了api,并设法得到了正确的响应。

try {
        URL url = new URL(FullURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();          
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        conn.setReadTimeout(9000);
        String input = "{\"accNo\": \"" + accNo + "\",\"token\": \"" + aToken +"\"}";   

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        Integer HTTPResponse = conn.getResponseCode();
        if(HTTPResponse != 200) 
        {
            //System.out.println("HTTP Response Code: " + conn.getResponseCode());
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        StringBuilder buf = new StringBuilder();
        char[] cbuf = new char[ 2048 ];
        int num;

        while ( -1 != (num=reader.read(cbuf)))
        {
            buf.append( cbuf, 0, num );
        }

        output = buf.toString();
        conn.disconnect();
        reader.close();
      }
dm7nw8vv

dm7nw8vv1#

我发现问题是由

setDoOutput(true)

它将隐式地将request方法设置为post,因为目标方法是get,所以服务器将抛出405 method not allow error。

相关问题