在向Web服务发出HTTP请求时出现405错误

时间:2017-01-05 12:12:26

标签: java web-services rest jax-rs jersey-2.0

我正在将基本java程序的HTTP GET请求发送到恰好是"http://localhost:9992/users/john.doe@example.com"的URL:

public class Tester {
    public static void main(String[] args) {
        HttpRequester.doesUserExist("john.doe@example.com");
    }
}

HTTPRequester的实施是这样的:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequester {
    private static HttpURLConnection connection = null;

    public static boolean doesUserExist(final String email) {
    final String targetUrl = Constants.URL_USER_SRVC +  email;
    System.out.println(targetUrl);
    try {
        URL url = new URL(targetUrl);
        connection = (HttpURLConnection) url.openConnection();
        System.out.println(connection.getRequestMethod());
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setUseCaches(false);
        connection.setDoOutput(true);

        DataOutputStream outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(email);
        outputStream.close();

            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer response = new StringBuffer();
            String line;
            while((line = reader.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            reader.close();
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

嵌入在Grizzly服务器中的Web服务,这里是API:

@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {

    @GET
    public List<User> getUsers() {
        return UserService.getUsers();
    }

    @GET
    @Path("/{userEmail}")
    public User getUser(@PathParam("userEmail") String userEmail) {
        return UserService.getUser(userEmail);
    }
}

请注意,webservice和java程序是两个独立的项目。当我执行main方法时,我在控制台中输出了这个错误:

java.io.IOException: Server returned HTTP response code: 405 for URL: http://localhost:9992/users/john.doe@example.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
at com.axa.visualizr.auth.utils.HttpRequester.doesUserExist(HttpRequester.java:30)
at com.axa.visualizr.auth.core.Tester.main(Tester.java:8)

我认为奇怪的是,即使我导入at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627),错误也会输出此java.net.HttpURLConnection;。我尝试在该行上打开声明,但Eclipse声明它不是该类中的有效行号。

我不知道为什么我说setRequestMethod("GET")时不允许这种方法。也许这可能是因为java程序没有在任何类型的服务器上运行? Tester.java仅用于测试目的,最终我将HTTPRequester移动到另一个Web服务,并从Web服务A到Web服务B进行调用。

2 个答案:

答案 0 :(得分:4)

由于您在requestbody中传递了一些内容,因此java会将其解释为POST请求。请从代码中删除以下行并尝试:

DataOutputStream outputStream = new DataOutputStream(
                connection.getOutputStream());
        outputStream.writeBytes(email);
        outputStream.close();

答案 1 :(得分:0)

尝试以下代码:

final String targetUrl = Constants.URL_USER_SRVC +  URLEncoder.encode(email, "UTF-8");

而不是:final String targetUrl = Constants.URL_USER_SRVC + email;