Add HttpClientPostingTest
This commit is contained in:
parent
415e6ea607
commit
18c74487ec
|
@ -0,0 +1,147 @@
|
|||
package org.baeldung.httpclient;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.ClientProtocolException;
|
||||
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;
|
||||
|
||||
public class HttpClientPostingTest {
|
||||
private static final String SAMPLE_URL = "http://localhost:8080/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 ClientProtocolException, 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 ClientProtocolException, 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 ClientProtocolException, 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 ClientProtocolException, 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 ClientProtocolException, 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 ClientProtocolException, 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 ClientProtocolException, 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 = new ProgressEntityWrapper.ProgressListener() {
|
||||
@Override
|
||||
public void progress(final float 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
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;
|
||||
|
||||
public 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 static interface ProgressListener {
|
||||
void progress(float percentage);
|
||||
}
|
||||
|
||||
public static class CountingOutputStream extends FilterOutputStream {
|
||||
|
||||
private final ProgressListener listener;
|
||||
private long transferred;
|
||||
private long totalBytes;
|
||||
|
||||
public 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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
hello world
|
|
@ -34,6 +34,11 @@
|
|||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-fileupload</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
<version>1.3.1</version>
|
||||
</dependency>
|
||||
<!-- web -->
|
||||
|
||||
<dependency>
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import org.baeldung.web.dto.Foo;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
// used to test HttpClientPostingTest
|
||||
@RestController
|
||||
public class SimplePostController {
|
||||
|
||||
@RequestMapping(value = "/users", method = RequestMethod.POST)
|
||||
public String postUser(@RequestParam final String username, @RequestParam final String password) {
|
||||
return "Success" + username;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
|
||||
public String postUserDetail(@RequestBody final Foo entity) {
|
||||
return "Success" + entity.getId();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
|
||||
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded " + username;
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
|
||||
public String postMultipart(@RequestParam("file") final MultipartFile file) {
|
||||
if (!file.isEmpty()) {
|
||||
try {
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
|
||||
final String fileName = dateFormat.format(new Date());
|
||||
final File fileServer = new File(fileName);
|
||||
fileServer.createNewFile();
|
||||
final byte[] bytes = file.getBytes();
|
||||
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
|
||||
stream.write(bytes);
|
||||
stream.close();
|
||||
return "You successfully uploaded ";
|
||||
} catch (final Exception e) {
|
||||
return "You failed to upload " + e.getMessage();
|
||||
}
|
||||
} else {
|
||||
return "You failed to upload because the file was empty.";
|
||||
}
|
||||
}
|
||||
}
|
|
@ -3,4 +3,14 @@
|
|||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd" >
|
||||
|
||||
<bean id="multipartResolver"
|
||||
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
|
||||
<!-- max upload size in bytes -->
|
||||
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
|
||||
|
||||
<!-- max size of file in memory (in bytes) -->
|
||||
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
|
||||
|
||||
</bean>
|
||||
|
||||
</beans>
|
Loading…
Reference in New Issue