1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 package org.apache.commons.httpclient;
32
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35
36 import junit.framework.Test;
37 import junit.framework.TestSuite;
38
39 import org.apache.commons.httpclient.methods.PostMethod;
40 import org.apache.commons.httpclient.methods.RequestEntity;
41 import org.apache.commons.httpclient.methods.StringRequestEntity;
42
43 /***
44 * Tests basic method functionality.
45 *
46 * @author Remy Maucherat
47 * @author Rodney Waldhoff
48 *
49 * @version $Id: TestPostMethod.java,v 1.3 2004/11/01 02:21:15 mbecke Exp $
50 */
51 public class TestPostMethod extends HttpClientTestBase {
52
53 static final String NAME = "name", VALUE = "value";
54 static final String NAME0 = "name0", VALUE0 = "value0";
55 static final String NAME1 = "name1", VALUE1 = "value1";
56 static final String NAME2 = "name2", VALUE2 = "value2";
57
58 static final NameValuePair PAIR = new NameValuePair(NAME, VALUE);
59 static final NameValuePair PAIR0 = new NameValuePair(NAME0, VALUE0);
60 static final NameValuePair PAIR1 = new NameValuePair(NAME1, VALUE1);
61 static final NameValuePair PAIR2 = new NameValuePair(NAME2, VALUE2);
62
63 public TestPostMethod(final String testName) throws IOException {
64 super(testName);
65 }
66
67 public static Test suite() {
68 TestSuite suite = new TestSuite(TestPostMethod.class);
69 ProxyTestDecorator.addTests(suite);
70 return suite;
71 }
72
73 public static void main(String args[]) {
74 String[] testCaseName = { TestPostMethod.class.getName() };
75 junit.textui.TestRunner.main(testCaseName);
76 }
77
78 private String getRequestAsString(RequestEntity entity) throws Exception {
79 ByteArrayOutputStream bos = new ByteArrayOutputStream();
80 entity.writeRequest(bos);
81 return new String(bos.toByteArray(), "UTF-8");
82 }
83
84 public void testPostParametersEncoding() throws Exception {
85 PostMethod post = new PostMethod();
86 post.setRequestBody(new NameValuePair[] { PAIR });
87 assertEquals("name=value", getRequestAsString(post.getRequestEntity()));
88
89 post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2 });
90 assertEquals("name=value&name1=value1&name2=value2",
91 getRequestAsString(post.getRequestEntity()));
92
93 post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2, new NameValuePair("hasSpace", "a b c d") });
94 assertEquals("name=value&name1=value1&name2=value2&hasSpace=a+b+c+d",
95 getRequestAsString(post.getRequestEntity()));
96
97 }
98
99 public void testPostSetRequestBody() throws Exception {
100 PostMethod post = new PostMethod("/foo");
101 String body = "this+is+the+body";
102 post.setRequestEntity(new StringRequestEntity(body));
103 assertEquals(body, getRequestAsString(post.getRequestEntity()));
104 }
105
106 }