如何向基于Apache CXF的服务发送请求和接收响应?

时间:2013-10-06 17:50:55

标签: java web-services rest

我有几个servlet,

  1. 将JSON编码的请求作为输入,
  2. 处理它们和
  3. 将对客户端的响应作为JSON编码对象返回。
  4. 到目前为止,我使用Android作为客户端(示例Android代码见下文)。

    现在我想编写一个普通的旧Java程序,它将发送请求并接收响应(与Android代码相同)。为此,我编写了一个Java测试(代码见下文, Java代码部分)并运行它。

    在客户端,我收到此错误:

    21:43:38.930 [main] ERROR r.a.c.t.TestAcceptanceProcedure1 - 
    java.io.IOException: Server returned HTTP response code: 405 for URL: http://myserver/myapp/rest/GetUserIdService
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441) ~[na:1.6.0_23]
        at testclient.TestAcceptanceProcedure1.test(TestAcceptanceProcedure1.java:47) ~[test-classes/:na]
    

    在服务器日志中,我看到以下消息:

    WARNING: No operation matching request path "/myapp/rest/GetUserIdService" is found, Relative Path: /, HTTP Method: GET, ContentType: */*, Accept: text/html,image/gif,image/jpeg,*/*,*/*;q=.2,. Please enable FINE/TRACE log level for more details
    

    问题:我应该如何更改Java测试以修复此错误?

    请注意,服务器已启动并正在运行(当我执行Android代码时,它可以正常运行)。

    Android代码:

    发送请求并收到回复:

    final GetSimulationStatusRequest request = new GetSimulationStatusRequest();
    final String json = Utils.convertToJson(request, getClass());
    final String serverUrl = Utils.getServerUrl(this, "GetSimulationStatusService");
    
    final IGetSimulationStatusAsyncTask getSimulationStatusTask = 
            asyncTaskFactory.createGetSimulationStatusAsyncTask(getWebServiceHelper());
    
    Utils.setRequestAndServerUrl(json, serverUrl, getSimulationStatusTask);
    
    final GetSimulationStatusResponse simulationStatusReponse = 
            getSimulationStatusTask.get();
    

    Utils.convertToJson:

    public static String convertToJson(final Object aRequest, Class<? extends Activity> aClass) {
        final ObjectMapper mapper = new ObjectMapper();
        String json = null;
    
        try {
            json = mapper.writeValueAsString(aRequest);
        } catch (final JsonProcessingException exception) {
            Log.e(aClass.getSimpleName(), exception.getLocalizedMessage(),
                    exception);
        }
        return json;
    }
    

    Utils.setRequestAndServerUrl:

    public static void setRequestAndServerUrl(final String aJson,
            final String aServerUrl, final IAsyncTask aTask) {
        aTask.addNameValuePair("request", aJson);
        aTask.sendRequest(new String[] { aServerUrl });
    }
    

    GetSimulationStatusAsyncTask:

    public class GetSimulationStatusAsyncTask 
        extends AsyncTask<String, String, GetSimulationStatusResponse> 
        implements IGetSimulationStatusAsyncTask {
        private static final String TAG = GetSimulationStatusAsyncTask.class.getSimpleName();
        private IWebServiceTaskHelper helper;
        private ICcpResponseParser<GetSimulationStatusResponse> responseParser = 
                new CcpResponseParser<GetSimulationStatusResponse>();
    
    
        public GetSimulationStatusAsyncTask(final IWebServiceTaskHelper aHelper) {
            helper = aHelper;
        }
    
        @Override
        public void addNameValuePair(final String aName, final String aValue) {
            helper.addNameValuePair(aName, aValue);
        }
    
        @Override
        protected GetSimulationStatusResponse doInBackground(String... aArgs) {
            return (GetSimulationStatusResponse)Utils.processResponse(this.helper, TAG, responseParser, 
                    GetSimulationStatusResponse.class, aArgs);
        }
    
        @Override
        public void sendRequest(final String[] aArgs) {
            execute(aArgs);
        }
    }
    

    Java代码:

    @Test
    public void test() throws JsonProcessingException, MalformedURLException {
        final GetUserIdRequest request = new GetUserIdRequest();
    
        request.setDeviceId("PC1");
    
        final String requestAsString = convertToJson(request);
        final String serverUrl = getServerUrl("GetUserIdService");
    
        final URL url = new URL(serverUrl);
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
    
            connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("request", requestAsString);
            connection.connect();
    
            inputStream = connection.getInputStream();
            final String responseAsString = IOUtils.toString(inputStream);
    
            LOGGER.debug("responseAsString: " + responseAsString);
    
        } catch (final IOException exception) {
            LOGGER.error("", exception);
        }
        finally
        {
            IOUtils.closeQuietly(inputStream);
        }
    }
    
    private String convertToJson(final GetUserIdRequest aRequest) throws JsonProcessingException {
        final ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(aRequest);
    }
    
    private String getServerUrl(final String aServiceName)
    {
        return "http://myserver.com/myapp/rest/" + aServiceName;
    }
    

    更新1(09.10.2013 12:23 MSK):

    @Path("/GetSimulationStatusService")
    public class GetSimulationStatusService extends BaseCcpService  {
      private GetSimulationStatusRequestParser requestParser = 
          new GetSimulationStatusRequestParser();
    
      @POST
      @Produces("text/plain")
      public String getSimulationStatus(@FormParam("request") final String aRequestJson) 
          throws JsonProcessingException
      {
        final GetSimulationStatusRequest request = requestParser.convert(aRequestJson);
    
        final GetSimulationStatusResponse response = new GetSimulationStatusResponse();
    
        response.setRequestId(request.getId());
        response.setCycle(getPersistence().getCurrentCycle(request.getUserId()));
        response.setLabourForce(getPersistence().getLabourForceSimulationParameter(
            request.getUserId()));
    
        return getObjectMapper().writeValueAsString(response);
      }
    }
    

    更新2(09.10.2013 20:48 MSK):当我更改如下所示的代码时,我得到500个HTTP响应。在服务器端,方法aRequest的{​​{1}}参数为空。

    GetUserIdService.getUserId

    更新3(09.10.2013 23:15):这个有效:

            connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("request", requestAsString);
            connection.setRequestMethod("POST"); // Added this line
            connection.connect();
    

1 个答案:

答案 0 :(得分:1)

405 HTTP错误代码表示端点不支持给定方法(GET)。可能代替GET请求你想发送POST。我不知道Android客户端发送了什么样的请求。

您是否有端点规范/文档?

Here您将找到有关如何使用普通Java API调用POST的信息。如果您可以在测试中使用外部库,那么使用RESTEasy可以更轻松地实现它。