错误 405 – 方法未在 Java HTTP 函数调用中找到

huangapple go评论69阅读模式
英文:

Error 405 - Method Not Found on Java HTTP function call

问题

需要帮助解决这段代码。在使用“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();
}
英文:

Need help on this piece of code. It's working fine on "POST" method. But when i changed it to "GET" for another API that accept GET method, it encounter 405 error.

P/S: I've tested the API using POSTMAN and managed to get proper respond.

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

答案1

得分: 0

我已经找到问题所在,是由于

setDoOutput(true)

它会隐式地将请求方法设置为POST,由于目标方法是GET,服务器将抛出405方法不允许的错误。

英文:

I've found the issue, was caused by the

setDoOutput(true)

It will implicitly set the request method to POST, since the targeted method is GET, the server will throw an 405 Method not allow error.

huangapple
  • 本文由 发表于 2020年8月21日 04:00:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63512388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定