简体   繁体   English

405发送HTTP请求时抛出错误JAVA

[英]405 Error when sending HTTP request throw JAVA

I try to send http request and get the result with a Java code 我尝试发送http请求并使用Java代码获取结果

this is the Server side: 这是服务器端:

public class Testws {
@GET
    @Path("/test/{id}")
    @Produces("application/xml")
    public Integer getAssets(@PathParam("id") int id){
        }
}

And this is the Client side: 这是客户端:

URL url = new URL("http://xxx/route/test/1");
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.connect();
final int responseCode = connection.getResponseCode();

when i run this java code i got an 405 status code but when i put the link ( http://xxx/route/test/1 ) directly in the browser it works fine i got 200 as a response code. 当我运行此Java代码时,我得到了405状态代码,但是当我直接在浏览器中放置链接( http:// xxx / route / test / 1 )时,它工作正常,我得到了200作为响应代码。 How can i fix this ? 我怎样才能解决这个问题 ?

Your error means that you query the server with the wrong HTTP method. 您的错误意味着您使用错误的HTTP方法查询服务器。

What you paste in your browser will be sent as GET method. 您在浏览器中粘贴的内容将作为GET方法发送。

Your code doesn't use GET , so to force an HTTP method, use HttpConnection.setRequestMethod 您的代码未使用GET ,因此要强制使用HTTP方法,请使用HttpConnection.setRequestMethod

Alternatively, setDoOutput(true) won't make you use GET , see this topic : What exactly does URLConnection.setDoOutput() affect? 另外, setDoOutput(true)不会使您使用GET ,请参阅本主题: URLConnection.setDoOutput()究竟会产生什么影响? .

Remove this line and you will use the default HTTP method, which is GET . 删除此行,您将使用默认的HTTP方法GET

public void setRequestMethod(String method) throws ProtocolException 公共无效setRequestMethod(String方法)抛出ProtocolException

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions. 设置URL请求的方法,方法之一:GET POST HEAD OPTIONS PUT DELETE TRACE合法,受协议限制。 The default method is GET . 默认方法是GET

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

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