Merge branch 'master' into BAEL-13599
This commit is contained in:
@@ -1,144 +0,0 @@
|
||||
package org.baeldung.httpclient;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.auth.AuthenticationException;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.fluent.Form;
|
||||
import org.apache.http.client.fluent.Request;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-rest to be running
|
||||
*/
|
||||
public class HttpClientPostingLiveTest {
|
||||
private static final String SAMPLE_URL = "http://localhost:8082/spring-rest/users";
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||
private static final String DEFAULT_USER = "test";
|
||||
private static final String DEFAULT_PASS = "test";
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
|
||||
|
||||
final List<NameValuePair> params = new ArrayList<NameValuePair>();
|
||||
params.add(new BasicNameValuePair("username", DEFAULT_USER));
|
||||
params.add(new BasicNameValuePair("password", DEFAULT_PASS));
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(params));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws IOException, AuthenticationException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
|
||||
httpPost.setEntity(new StringEntity("test post"));
|
||||
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostJsonUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
|
||||
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
final StringEntity entity = new StringEntity(json);
|
||||
httpPost.setEntity(entity);
|
||||
httpPost.setHeader("Accept", "application/json");
|
||||
httpPost.setHeader("Content-type", "application/json");
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
|
||||
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
|
||||
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addTextBody("username", DEFAULT_USER);
|
||||
builder.addTextBody("password", DEFAULT_PASS);
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
httpPost.setEntity(multipart);
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUploadFileUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
httpPost.setEntity(multipart);
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws IOException {
|
||||
final CloseableHttpClient client = HttpClients.createDefault();
|
||||
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
|
||||
|
||||
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
|
||||
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
|
||||
final HttpEntity multipart = builder.build();
|
||||
|
||||
final ProgressEntityWrapper.ProgressListener pListener = percentage -> assertFalse(Float.compare(percentage, 100) > 0);
|
||||
|
||||
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
|
||||
|
||||
final CloseableHttpResponse response = client.execute(httpPost);
|
||||
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
|
||||
client.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package org.baeldung.httpclient;
|
||||
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.entity.HttpEntityWrapper;
|
||||
|
||||
public class ProgressEntityWrapper extends HttpEntityWrapper {
|
||||
private final ProgressListener listener;
|
||||
|
||||
ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
|
||||
super(entity);
|
||||
this.listener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(final OutputStream outstream) throws IOException {
|
||||
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
|
||||
}
|
||||
|
||||
public interface ProgressListener {
|
||||
void progress(float percentage);
|
||||
}
|
||||
|
||||
public static class CountingOutputStream extends FilterOutputStream {
|
||||
|
||||
private final ProgressListener listener;
|
||||
private long transferred;
|
||||
private long totalBytes;
|
||||
|
||||
CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
|
||||
super(out);
|
||||
this.listener = listener;
|
||||
transferred = 0;
|
||||
this.totalBytes = totalBytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(final byte[] b, final int off, final int len) throws IOException {
|
||||
out.write(b, off, len);
|
||||
transferred += len;
|
||||
listener.progress(getCurrentProgress());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(final int b) throws IOException {
|
||||
out.write(b);
|
||||
transferred++;
|
||||
listener.progress(getCurrentProgress());
|
||||
}
|
||||
|
||||
private float getCurrentProgress() {
|
||||
return ((float) transferred / totalBytes) * 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
package org.baeldung.httpclient.sec;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpHost;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.auth.AuthScope;
|
||||
import org.apache.http.auth.UsernamePasswordCredentials;
|
||||
import org.apache.http.client.AuthCache;
|
||||
import org.apache.http.client.CredentialsProvider;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.impl.auth.BasicScheme;
|
||||
import org.apache.http.impl.client.BasicAuthCache;
|
||||
import org.apache.http.impl.client.BasicCredentialsProvider;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.baeldung.httpclient.ResponseUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
/*
|
||||
* NOTE : Need module spring-security-rest-basic-auth to be running
|
||||
*/
|
||||
|
||||
public class HttpClientAuthLiveTest {
|
||||
|
||||
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1";
|
||||
private static final String DEFAULT_USER = "user1";
|
||||
private static final String DEFAULT_PASS = "user1Pass";
|
||||
|
||||
private CloseableHttpClient client;
|
||||
|
||||
private CloseableHttpResponse response;
|
||||
|
||||
@Before
|
||||
public final void before() {
|
||||
client = HttpClientBuilder.create().build();
|
||||
}
|
||||
|
||||
@After
|
||||
public final void after() throws IllegalStateException, IOException {
|
||||
ResponseUtil.closeResponse(response);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider()).build();
|
||||
|
||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAuthenticationIsPreemptive_whenExecutingBasicGetRequestWithBasicAuthenticationEnabled_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().build();
|
||||
response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION), context());
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess() throws IOException {
|
||||
client = HttpClientBuilder.create().build();
|
||||
|
||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader(DEFAULT_USER, DEFAULT_PASS));
|
||||
response = client.execute(request);
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
|
||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
|
||||
final String authHeader = "Basic " + new String(encodedAuth);
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
|
||||
|
||||
client = HttpClientBuilder.create().build();
|
||||
response = client.execute(request);
|
||||
|
||||
final int statusCode = response.getStatusLine().getStatusCode();
|
||||
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
|
||||
}
|
||||
|
||||
// UTILS
|
||||
|
||||
private CredentialsProvider provider() {
|
||||
final CredentialsProvider provider = new BasicCredentialsProvider();
|
||||
final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
|
||||
provider.setCredentials(AuthScope.ANY, credentials);
|
||||
return provider;
|
||||
}
|
||||
|
||||
private HttpContext context() {
|
||||
final HttpHost targetHost = new HttpHost("localhost", 8080, "http");
|
||||
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
|
||||
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS));
|
||||
|
||||
// Create AuthCache instance
|
||||
final AuthCache authCache = new BasicAuthCache();
|
||||
// Generate BASIC scheme object and add it to the local auth cache
|
||||
authCache.put(targetHost, new BasicScheme());
|
||||
|
||||
// Add AuthCache to the execution context
|
||||
final HttpClientContext context = HttpClientContext.create();
|
||||
context.setCredentialsProvider(credsProvider);
|
||||
context.setAuthCache(authCache);
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
private String authorizationHeader(final String username, final String password) {
|
||||
final String auth = username + ":" + password;
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
|
||||
|
||||
return "Basic " + new String(encodedAuth);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user