Apache Http客户端在浏览器中获取JSON时提供错误请求

时间:2015-01-28 10:42:28

标签: java json apache-httpclient-4.x bad-request

我有一个Java应用程序,我想连接到REST服务。我想连接到Jira实例以获取一些项目详细信息作为JSON。

这是我的类,用于连接和从休息服务获取JSON

public String connect() throws CustomException, IOException {

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        try {

            UrlValidator validator = new UrlValidator();
            if (!validator.isValid(webServiceUrl)) {
                throw new CustomException("URL is invalid.");
            }
            String encode = userName + COLON + password;
            String auth = Base64Encoder.encode(encode.getBytes());
            HttpGet request = new HttpGet(webServiceUrl);
            request.addHeader(HttpHeaders.AUTHORIZATION, BASIC + auth);
            request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            request.addHeader(HttpHeaders.ACCEPT, "application/json");
            HttpResponse response = httpClient.execute(request);
            stringResponse = getStatusBody(response);
        } catch (HttpHostConnectException e) {
            throw new CustomException("URL is invalid.");
        } catch (ConnectTimeoutException e) {
            throw new CustomException("URL is invalid.");
        } finally {
            httpClient.getConnectionManager().shutdown();

        }
        return stringResponse;
    }

    private String getStatusBody(HttpResponse response) throws CustomException,
            IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        switch (statusCode) {
        case HttpStatus.SC_OK:
            String contentType = response.getHeaders(HttpHeaders.CONTENT_TYPE)[0]
                    .getValue();
            if (contentType.contains(TEXT_HTML)) {
                throw new CustomException("URL is invalid.");
            } else {
                stringResponse = new BasicResponseHandler()
                        .handleResponse(response);
            }
            break;
        case HttpStatus.SC_NOT_FOUND:
            throw new CustomException("URL is invalid.");
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_FORBIDDEN:
            throw new CustomException("Invalid username and/or password.");
        default:
            throw new HttpResponseException(statusCode, response
                    .getStatusLine().getReasonPhrase());
        }
        return stringResponse;
    }

当我使用带有Jira中存在的项目名称的URL运行以下内容时,它正常工作并提供JSON响应。 但是,如果我提供的网址为

http://jira.mydomain.com/rest/api/2/search?jql=project=projectname

工作正常,因为Jira中有项目名称​​ projectname

http://jira.mydomain.com/rest/api/2/search?jql=project=project 

它提供了错误的请求异常,因为Jira中没有名称为 project 的项目。

问题是如果我在谷歌浏览器中的浏览器或POSTMAN客户端中尝试URL,它会给出一个带有错误信息的JSON,如下所示

{
    "errorMessages": [
        "The value 'project' does not exist for the field 'project'."
    ],
    "errors": {}
}

但是通过代码,以下异常我会收到错误请求。

org.apache.http.client.HttpResponseException: Bad Request
    at com.app.rest.RestHttpClient.getStatusBody(RestHttpClient.java:114)
    at com.app.rest.RestHttpClient.connect(RestHttpClient.java:81)
    at com.app.rest.Connector.connect(Connector.java:39)
    at com.app.rest.connector.SourceConnector.connect(SourceConnector.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:146)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:277)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

为什么在浏览器中我获得JSON并且在Apache Http客户端中我收到错误的请求?

我正在使用Apache HTTP客户端4.2.5版本。

0 个答案:

没有答案