英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论