View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.testing.fluent;
28  
29  import java.io.File;
30  import java.io.IOException;
31  import java.net.URI;
32  import java.nio.charset.StandardCharsets;
33  
34  import org.apache.hc.client5.http.ClientProtocolException;
35  import org.apache.hc.client5.http.fluent.Content;
36  import org.apache.hc.client5.http.fluent.Request;
37  import org.apache.hc.client5.testing.sync.LocalServerTestBase;
38  import org.apache.hc.core5.http.ClassicHttpRequest;
39  import org.apache.hc.core5.http.ClassicHttpResponse;
40  import org.apache.hc.core5.http.ContentType;
41  import org.apache.hc.core5.http.HttpEntity;
42  import org.apache.hc.core5.http.HttpException;
43  import org.apache.hc.core5.http.HttpHost;
44  import org.apache.hc.core5.http.io.HttpClientResponseHandler;
45  import org.apache.hc.core5.http.io.HttpRequestHandler;
46  import org.apache.hc.core5.http.io.entity.EntityUtils;
47  import org.apache.hc.core5.http.io.entity.StringEntity;
48  import org.apache.hc.core5.http.protocol.HttpContext;
49  import org.junit.Assert;
50  import org.junit.Before;
51  import org.junit.Test;
52  
53  public class TestFluent extends LocalServerTestBase {
54  
55      @Before
56      public void setUp() throws Exception {
57          this.server.registerHandler("/", new HttpRequestHandler() {
58  
59              @Override
60              public void handle(
61                      final ClassicHttpRequest request,
62                      final ClassicHttpResponse response,
63                      final HttpContext context) throws HttpException, IOException {
64                  response.setEntity(new StringEntity("All is well", ContentType.TEXT_PLAIN));
65              }
66  
67          });
68          this.server.registerHandler("/echo", new HttpRequestHandler() {
69  
70              @Override
71              public void handle(
72                      final ClassicHttpRequest request,
73                      final ClassicHttpResponse response,
74                      final HttpContext context) throws HttpException, IOException {
75                  HttpEntity responseEntity = null;
76                  final HttpEntity requestEntity = request.getEntity();
77                  if (requestEntity != null) {
78                      final String contentTypeStr = requestEntity.getContentType();
79                      final ContentType contentType = contentTypeStr == null ? ContentType.DEFAULT_TEXT : ContentType.parse(contentTypeStr);
80                      if (ContentType.TEXT_PLAIN.getMimeType().equals(contentType.getMimeType())) {
81                          responseEntity = new StringEntity(
82                                  EntityUtils.toString(requestEntity), ContentType.TEXT_PLAIN);
83                      }
84                  }
85                  if (responseEntity == null) {
86                      responseEntity = new StringEntity("echo", ContentType.TEXT_PLAIN);
87                  }
88                  response.setEntity(responseEntity);
89              }
90  
91          });
92      }
93  
94      @Test
95      public void testGetRequest() throws Exception {
96          final HttpHost target = start();
97          final String baseURL = "http://localhost:" + target.getPort();
98          final String message = Request.get(baseURL + "/").execute().returnContent().asString();
99          Assert.assertEquals("All is well", message);
100     }
101 
102     @Test
103     public void testGetRequestByName() throws Exception {
104         final HttpHost target = start();
105         final String baseURL = "http://localhost:" + target.getPort();
106         final String message = Request.create("GET", baseURL + "/").execute().returnContent().asString();
107         Assert.assertEquals("All is well", message);
108     }
109 
110     @Test
111     public void testGetRequestByNameWithURI() throws Exception {
112         final HttpHost target = start();
113         final String baseURL = "http://localhost:" + target.getPort();
114         final String message = Request.create("GET", new URI(baseURL + "/")).execute().returnContent().asString();
115         Assert.assertEquals("All is well", message);
116     }
117 
118     @Test(expected = ClientProtocolException.class)
119     public void testGetRequestFailure() throws Exception {
120         final HttpHost target = start();
121         final String baseURL = "http://localhost:" + target.getPort();
122         Request.get(baseURL + "/boom").execute().returnContent().asString();
123     }
124 
125     @Test
126     public void testPostRequest() throws Exception {
127         final HttpHost target = start();
128         final String baseURL = "http://localhost:" + target.getPort();
129         final String message1 = Request.post(baseURL + "/echo")
130                 .bodyString("what is up?", ContentType.TEXT_PLAIN)
131                 .execute().returnContent().asString();
132         Assert.assertEquals("what is up?", message1);
133         final String message2 = Request.post(baseURL + "/echo")
134                 .bodyByteArray(new byte[]{1, 2, 3}, ContentType.APPLICATION_OCTET_STREAM)
135                 .execute().returnContent().asString();
136         Assert.assertEquals("echo", message2);
137     }
138 
139     @Test
140     public void testContentAsStringWithCharset() throws Exception {
141         final HttpHost target = start();
142         final String baseURL = "http://localhost:" + target.getPort();
143         final Content content = Request.post(baseURL + "/echo").bodyByteArray("Ü".getBytes(StandardCharsets.UTF_8)).execute()
144                 .returnContent();
145         Assert.assertEquals((byte)-61, content.asBytes()[0]);
146         Assert.assertEquals((byte)-100, content.asBytes()[1]);
147         Assert.assertEquals("Ü", content.asString(StandardCharsets.UTF_8));
148     }
149 
150     @Test
151     public void testConnectionRelease() throws Exception {
152         final HttpHost target = start();
153         final String baseURL = "http://localhost:" + target.getPort();
154         for (int i = 0; i < 20; i++) {
155             Request.get(baseURL + "/").execute().returnContent();
156             Request.get(baseURL + "/").execute().returnResponse();
157             Request.get(baseURL + "/").execute().discardContent();
158             Request.get(baseURL + "/").execute().handleResponse(new HttpClientResponseHandler<Object>() {
159 
160                 @Override
161                 public Object handleResponse(
162                         final ClassicHttpResponse response) throws IOException {
163                     return null;
164                 }
165 
166             });
167             final File tmpFile = File.createTempFile("test", ".bin");
168             try {
169                 Request.get(baseURL + "/").execute().saveContent(tmpFile);
170             } finally {
171                 tmpFile.delete();
172             }
173         }
174     }
175 
176 }