Skip to content

Commit 3fd4c34

Browse files
author
Eugen
committed
Merge pull request eugenp#105 from Doha2012/master
Add HttpClientPostingTest
2 parents 01548ef + eedcbeb commit 3fd4c34

File tree

6 files changed

+295
-0
lines changed

6 files changed

+295
-0
lines changed
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
package org.baeldung.httpclient;
2+
3+
import static org.hamcrest.Matchers.equalTo;
4+
import static org.junit.Assert.assertFalse;
5+
import static org.junit.Assert.assertThat;
6+
7+
import java.io.File;
8+
import java.io.IOException;
9+
import java.util.ArrayList;
10+
import java.util.List;
11+
12+
import org.apache.http.HttpEntity;
13+
import org.apache.http.HttpResponse;
14+
import org.apache.http.NameValuePair;
15+
import org.apache.http.auth.AuthenticationException;
16+
import org.apache.http.auth.UsernamePasswordCredentials;
17+
import org.apache.http.client.ClientProtocolException;
18+
import org.apache.http.client.entity.UrlEncodedFormEntity;
19+
import org.apache.http.client.fluent.Form;
20+
import org.apache.http.client.fluent.Request;
21+
import org.apache.http.client.methods.CloseableHttpResponse;
22+
import org.apache.http.client.methods.HttpPost;
23+
import org.apache.http.entity.ContentType;
24+
import org.apache.http.entity.StringEntity;
25+
import org.apache.http.entity.mime.MultipartEntityBuilder;
26+
import org.apache.http.impl.auth.BasicScheme;
27+
import org.apache.http.impl.client.CloseableHttpClient;
28+
import org.apache.http.impl.client.HttpClients;
29+
import org.apache.http.message.BasicNameValuePair;
30+
import org.junit.Test;
31+
32+
public class HttpClientPostingTest {
33+
private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users";
34+
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
35+
private static final String DEFAULT_USER = "test";
36+
private static final String DEFAULT_PASS = "test";
37+
38+
@Test
39+
public void whenSendPostRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
40+
final CloseableHttpClient client = HttpClients.createDefault();
41+
final HttpPost httpPost = new HttpPost(SAMPLE_URL);
42+
43+
final List<NameValuePair> params = new ArrayList<NameValuePair>();
44+
params.add(new BasicNameValuePair("username", DEFAULT_USER));
45+
params.add(new BasicNameValuePair("password", DEFAULT_PASS));
46+
httpPost.setEntity(new UrlEncodedFormEntity(params));
47+
48+
final CloseableHttpResponse response = client.execute(httpPost);
49+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
50+
client.close();
51+
}
52+
53+
@Test
54+
public void whenSendPostRequestWithAuthorizationUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException, AuthenticationException {
55+
final CloseableHttpClient client = HttpClients.createDefault();
56+
final HttpPost httpPost = new HttpPost(URL_SECURED_BY_BASIC_AUTHENTICATION);
57+
58+
httpPost.setEntity(new StringEntity("test post"));
59+
final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(DEFAULT_USER, DEFAULT_PASS);
60+
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
61+
62+
final CloseableHttpResponse response = client.execute(httpPost);
63+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
64+
client.close();
65+
}
66+
67+
@Test
68+
public void whenPostJsonUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
69+
final CloseableHttpClient client = HttpClients.createDefault();
70+
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/detail");
71+
72+
final String json = "{\"id\":1,\"name\":\"John\"}";
73+
final StringEntity entity = new StringEntity(json);
74+
httpPost.setEntity(entity);
75+
httpPost.setHeader("Accept", "application/json");
76+
httpPost.setHeader("Content-type", "application/json");
77+
78+
final CloseableHttpResponse response = client.execute(httpPost);
79+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
80+
client.close();
81+
}
82+
83+
@Test
84+
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws ClientProtocolException, IOException {
85+
final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();
86+
87+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
88+
}
89+
90+
@Test
91+
public void whenSendMultipartRequestUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
92+
final CloseableHttpClient client = HttpClients.createDefault();
93+
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/multipart");
94+
95+
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
96+
builder.addTextBody("username", DEFAULT_USER);
97+
builder.addTextBody("password", DEFAULT_PASS);
98+
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
99+
final HttpEntity multipart = builder.build();
100+
101+
httpPost.setEntity(multipart);
102+
103+
final CloseableHttpResponse response = client.execute(httpPost);
104+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
105+
client.close();
106+
}
107+
108+
@Test
109+
public void whenUploadFileUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
110+
final CloseableHttpClient client = HttpClients.createDefault();
111+
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
112+
113+
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
114+
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
115+
final HttpEntity multipart = builder.build();
116+
117+
httpPost.setEntity(multipart);
118+
119+
final CloseableHttpResponse response = client.execute(httpPost);
120+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
121+
client.close();
122+
}
123+
124+
@Test
125+
public void whenGetUploadFileProgressUsingHttpClient_thenCorrect() throws ClientProtocolException, IOException {
126+
final CloseableHttpClient client = HttpClients.createDefault();
127+
final HttpPost httpPost = new HttpPost(SAMPLE_URL + "/upload");
128+
129+
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
130+
builder.addBinaryBody("file", new File("src/test/resources/test.in"), ContentType.APPLICATION_OCTET_STREAM, "file.ext");
131+
final HttpEntity multipart = builder.build();
132+
133+
final ProgressEntityWrapper.ProgressListener pListener = new ProgressEntityWrapper.ProgressListener() {
134+
@Override
135+
public void progress(final float percentage) {
136+
assertFalse(Float.compare(percentage, 100) > 0);
137+
}
138+
};
139+
140+
httpPost.setEntity(new ProgressEntityWrapper(multipart, pListener));
141+
142+
final CloseableHttpResponse response = client.execute(httpPost);
143+
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
144+
client.close();
145+
}
146+
147+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package org.baeldung.httpclient;
2+
3+
import java.io.FilterOutputStream;
4+
import java.io.IOException;
5+
import java.io.OutputStream;
6+
7+
import org.apache.http.HttpEntity;
8+
import org.apache.http.entity.HttpEntityWrapper;
9+
10+
11+
public class ProgressEntityWrapper extends HttpEntityWrapper {
12+
private final ProgressListener listener;
13+
14+
public ProgressEntityWrapper(final HttpEntity entity, final ProgressListener listener) {
15+
super(entity);
16+
this.listener = listener;
17+
}
18+
19+
@Override
20+
public void writeTo(final OutputStream outstream) throws IOException {
21+
super.writeTo(new CountingOutputStream(outstream, listener, getContentLength()));
22+
}
23+
24+
public static interface ProgressListener {
25+
void progress(float percentage);
26+
}
27+
28+
public static class CountingOutputStream extends FilterOutputStream {
29+
30+
private final ProgressListener listener;
31+
private long transferred;
32+
private long totalBytes;
33+
34+
public CountingOutputStream(final OutputStream out, final ProgressListener listener, final long totalBytes) {
35+
super(out);
36+
this.listener = listener;
37+
transferred = 0;
38+
this.totalBytes = totalBytes;
39+
}
40+
41+
@Override
42+
public void write(final byte[] b, final int off, final int len) throws IOException {
43+
out.write(b, off, len);
44+
transferred += len;
45+
listener.progress(getCurrentProgress());
46+
}
47+
48+
@Override
49+
public void write(final int b) throws IOException {
50+
out.write(b);
51+
transferred++;
52+
listener.progress(getCurrentProgress());
53+
}
54+
55+
private float getCurrentProgress() {
56+
return ((float) transferred / totalBytes) * 100;
57+
}
58+
}
59+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
hello world

spring-rest/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@
3434
<version>${org.springframework.version}</version>
3535
</dependency>
3636

37+
<dependency>
38+
<groupId>commons-fileupload</groupId>
39+
<artifactId>commons-fileupload</artifactId>
40+
<version>1.3.1</version>
41+
</dependency>
3742
<!-- web -->
3843

3944
<dependency>
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package org.baeldung.web.controller;
2+
3+
import java.io.BufferedOutputStream;
4+
import java.io.File;
5+
import java.io.FileOutputStream;
6+
import java.text.DateFormat;
7+
import java.text.SimpleDateFormat;
8+
import java.util.Date;
9+
10+
import org.baeldung.web.dto.Foo;
11+
import org.springframework.web.bind.annotation.RequestBody;
12+
import org.springframework.web.bind.annotation.RequestMapping;
13+
import org.springframework.web.bind.annotation.RequestMethod;
14+
import org.springframework.web.bind.annotation.RequestParam;
15+
import org.springframework.web.bind.annotation.RestController;
16+
import org.springframework.web.multipart.MultipartFile;
17+
18+
// used to test HttpClientPostingTest
19+
@RestController
20+
public class SimplePostController {
21+
22+
@RequestMapping(value = "/users", method = RequestMethod.POST)
23+
public String postUser(@RequestParam final String username, @RequestParam final String password) {
24+
return "Success" + username;
25+
}
26+
27+
@RequestMapping(value = "/users/detail", method = RequestMethod.POST)
28+
public String postUserDetail(@RequestBody final Foo entity) {
29+
return "Success" + entity.getId();
30+
}
31+
32+
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
33+
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
34+
if (!file.isEmpty()) {
35+
try {
36+
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
37+
final String fileName = dateFormat.format(new Date());
38+
final File fileServer = new File(fileName);
39+
fileServer.createNewFile();
40+
final byte[] bytes = file.getBytes();
41+
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
42+
stream.write(bytes);
43+
stream.close();
44+
return "You successfully uploaded " + username;
45+
} catch (final Exception e) {
46+
return "You failed to upload " + e.getMessage();
47+
}
48+
} else {
49+
return "You failed to upload because the file was empty.";
50+
}
51+
}
52+
53+
@RequestMapping(value = "/users/upload", method = RequestMethod.POST)
54+
public String postMultipart(@RequestParam("file") final MultipartFile file) {
55+
if (!file.isEmpty()) {
56+
try {
57+
final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
58+
final String fileName = dateFormat.format(new Date());
59+
final File fileServer = new File(fileName);
60+
fileServer.createNewFile();
61+
final byte[] bytes = file.getBytes();
62+
final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
63+
stream.write(bytes);
64+
stream.close();
65+
return "You successfully uploaded ";
66+
} catch (final Exception e) {
67+
return "You failed to upload " + e.getMessage();
68+
}
69+
} else {
70+
return "You failed to upload because the file was empty.";
71+
}
72+
}
73+
}

spring-rest/src/main/webapp/WEB-INF/api-servlet.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,14 @@
33
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
44
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd" >
55

6+
<bean id="multipartResolver"
7+
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
8+
<!-- max upload size in bytes -->
9+
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
10+
11+
<!-- max size of file in memory (in bytes) -->
12+
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
13+
14+
</bean>
15+
616
</beans>

0 commit comments

Comments
 (0)