|
| 1 | +package org.baeldung.httpclient; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | + |
| 6 | +import org.apache.http.HttpEntity; |
| 7 | +import org.apache.http.auth.AuthenticationException; |
| 8 | +import org.apache.http.auth.UsernamePasswordCredentials; |
| 9 | +import org.apache.http.client.ClientProtocolException; |
| 10 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 11 | +import org.apache.http.client.methods.HttpPost; |
| 12 | +import org.apache.http.entity.StringEntity; |
| 13 | +import org.apache.http.impl.auth.BasicScheme; |
| 14 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 15 | +import org.apache.http.impl.client.HttpClientBuilder; |
| 16 | +import org.junit.After; |
| 17 | +import org.junit.Before; |
| 18 | +import org.junit.Test; |
| 19 | + |
| 20 | +public class HttpClientBasicPostLiveTest { |
| 21 | + |
| 22 | + private static final String SAMPLE_URL = "http://www.github.com"; |
| 23 | + |
| 24 | + private CloseableHttpClient instance; |
| 25 | + |
| 26 | + private CloseableHttpResponse response; |
| 27 | + |
| 28 | + @Before |
| 29 | + public final void before() { |
| 30 | + instance = HttpClientBuilder.create().build(); |
| 31 | + } |
| 32 | + |
| 33 | + @After |
| 34 | + public final void after() throws IllegalStateException, IOException { |
| 35 | + if (response == null) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + try { |
| 40 | + final HttpEntity entity = response.getEntity(); |
| 41 | + if (entity != null) { |
| 42 | + final InputStream instream = entity.getContent(); |
| 43 | + instream.close(); |
| 44 | + } |
| 45 | + } finally { |
| 46 | + response.close(); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + // tests - non-GET |
| 51 | + |
| 52 | + @Test |
| 53 | + public final void whenExecutingPostRequest_thenNoExceptions() throws ClientProtocolException, IOException { |
| 54 | + instance.execute(new HttpPost(SAMPLE_URL)); |
| 55 | + } |
| 56 | + |
| 57 | + @Test |
| 58 | + public final void whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException { |
| 59 | + final HttpPost request = new HttpPost(SAMPLE_URL); |
| 60 | + request.setEntity(new StringEntity("in the body of the POST")); |
| 61 | + instance.execute(request); |
| 62 | + } |
| 63 | + |
| 64 | + @Test |
| 65 | + public final void givenAuth_whenExecutingPostRequestWithBody_thenNoExceptions() throws ClientProtocolException, IOException, AuthenticationException { |
| 66 | + final HttpPost request = new HttpPost(SAMPLE_URL); |
| 67 | + request.setEntity(new StringEntity("in the body of the POST")); |
| 68 | + final UsernamePasswordCredentials creds = new UsernamePasswordCredentials("username", "password"); |
| 69 | + request.addHeader(new BasicScheme().authenticate(creds, request, null)); |
| 70 | + instance.execute(request); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments