@Test public void shouldSetTheAcceptHeaderWhilePostingProperties() throws Exception { HttpPost post = mock(HttpPost.class); when(httpClientFactory.createPost("url")).thenReturn(post); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); when(httpClient.execute(post)).thenReturn(response); ArgumentCaptor<UrlEncodedFormEntity> entityCaptor = ArgumentCaptor.forClass(UrlEncodedFormEntity.class); service.postProperty("url", "value"); verify(post).setHeader("Confirm","true"); verify(post).setEntity(entityCaptor.capture()); UrlEncodedFormEntity expected = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("value", "value"))); UrlEncodedFormEntity actual = entityCaptor.getValue(); assertEquals(IOUtils.toString(expected.getContent()), IOUtils.toString(actual.getContent())); assertEquals(expected.getContentLength(), expected.getContentLength()); assertEquals(expected.getContentType(), expected.getContentType()); assertEquals(expected.getContentEncoding(), expected.getContentEncoding()); assertEquals(expected.isChunked(), expected.isChunked()); }
/** * Creates a GET or POST request depending on configuration. * @return Either a GET or POST request. */ private HttpUriRequest createRequest(URIBuilder builder, Collection<NameValuePair> params) throws URISyntaxException, UnsupportedEncodingException { Collection<NameValuePair> p = getApiParams(); params.addAll(p); if(apiProperties.getUseHttpGet()) { for (NameValuePair nvp : params){ builder.addParameter(nvp.getName(), nvp.getValue()); } URI uri = builder.build(); getLogger().trace("CREATING GET: " + URLDecoder.decode(uri.toString(), "UTF-8")); return new HttpGet(uri); } else { URI uri = builder.build(); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Charset.forName("utf-8")); StringWriter writer = new StringWriter(); try { IOUtils.copy(formEntity.getContent(), writer, "utf-8"); } catch (IOException e) { getLogger().debug("Error when writing POST entity to string: " + e.getMessage(), e); } getLogger().trace("CREATING POST: " + URLDecoder.decode(uri.toString(), "UTF-8") + "?" + URLDecoder.decode(writer.toString(), "UTF-8")); HttpPost post = new HttpPost(uri); post.setEntity(formEntity); return post; } }