title: How to send requests and receive responses to/from an Apache CXF-based service?
body: <p>I have several servlets, which </p>
  
  <ol>
  <li>take JSON-encoded requests as inputs, </li>
  <li>process them and</li>
  <li>return responses to the client as JSON-encoded objects.</li>
  </ol>
  
  <p>Up to now I used Android as client (sample Android code see below).</p>
  
  <p>Now I want to write a plain old Java program, which would send requests and receive the responses (do the same as the Android code). For this purpose I wrote a Java test (code see below, section <em>Java code</em>) and ran it.</p>
  
  <p>At the client side I get this error:</p>
  
  <pre><code>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]
  </code></pre>
  
  <p>In the server log, I see this message:</p>
  
  <pre><code>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
  </code></pre>
  
  <p><strong>Question:</strong> How should I change my Java test to fix this error?</p>
  
  <p>Note that the server is up and running (when I execute the Android code, it works).</p>
  
  <p><strong>Android code:</strong></p>
  
  <p>Sending the request and receiving the response:</p>
  
  <pre><code>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();
  </code></pre>
  
  <p><strong>Utils.convertToJson:</strong></p>
  
  <pre><code>public static String convertToJson(final Object aRequest, Class&lt;? extends Activity&gt; 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;
  }
  </code></pre>
  
  <p><strong>Utils.setRequestAndServerUrl:</strong></p>
  
  <pre><code>public static void setRequestAndServerUrl(final String aJson,
          final String aServerUrl, final IAsyncTask aTask) {
      aTask.addNameValuePair("request", aJson);
      aTask.sendRequest(new String[] { aServerUrl });
  }
  </code></pre>
  
  <p><strong>GetSimulationStatusAsyncTask:</strong></p>
  
  <pre><code>public class GetSimulationStatusAsyncTask 
      extends AsyncTask&lt;String, String, GetSimulationStatusResponse&gt; 
      implements IGetSimulationStatusAsyncTask {
      private static final String TAG = GetSimulationStatusAsyncTask.class.getSimpleName();
      private IWebServiceTaskHelper helper;
      private ICcpResponseParser&lt;GetSimulationStatusResponse&gt; responseParser = 
              new CcpResponseParser&lt;GetSimulationStatusResponse&gt;();
  
  
      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);
      }
  }
  </code></pre>
  
  <p><strong>Java code:</strong></p>
  
  <pre><code>@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;
  }
  </code></pre>
  
  <p><strong>Update 1 (09.10.2013 12:23 MSK):</strong></p>
  
  <pre><code>@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);
    }
  }
  </code></pre>
  
  <p><strong>Update 2 (09.10.2013 20:48 MSK):</strong> When I change the code like shown below, I get 500 HTTP response. At the server side, the <code>aRequest</code> argument of the method <code>GetUserIdService.getUserId</code> is null.</p>
  
  <pre><code>        connection = (HttpURLConnection) url.openConnection();
          connection.addRequestProperty("request", requestAsString);
          connection.setRequestMethod("POST"); // Added this line
          connection.connect();
  </code></pre>
  
  <p><strong>Update 3 (09.10.2013 23:15):</strong> This one works:</p>
  
  <pre><code>@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;
      OutputStream outputStream = null;
      try {
  
          connection = (HttpURLConnection) url.openConnection();
          connection.setRequestMethod("POST");
          connection.setDoOutput(true);
          connection.connect();
  
          outputStream = connection.getOutputStream();
  
          IOUtils.write("request=" + requestAsString, outputStream);
  
          inputStream = connection.getInputStream();
          final String responseAsString = IOUtils.toString(inputStream);
  
          LOGGER.debug("responseAsString: " + responseAsString);
  
      } catch (final IOException exception) {
          LOGGER.error("", exception);
      }
      finally
      {
          IOUtils.closeQuietly(inputStream);
          IOUtils.closeQuietly(outputStream);
      }
  }
  </code></pre>