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  
28  package org.apache.hc.core5.http.examples;
29  
30  import java.io.IOException;
31  import java.io.OutputStream;
32  import java.nio.charset.StandardCharsets;
33  import java.util.concurrent.TimeUnit;
34  
35  import org.apache.hc.core5.http.ClassicHttpRequest;
36  import org.apache.hc.core5.http.ClassicHttpResponse;
37  import org.apache.hc.core5.http.ContentType;
38  import org.apache.hc.core5.http.HttpConnection;
39  import org.apache.hc.core5.http.HttpEntity;
40  import org.apache.hc.core5.http.HttpHost;
41  import org.apache.hc.core5.http.HttpRequest;
42  import org.apache.hc.core5.http.HttpResponse;
43  import org.apache.hc.core5.http.Method;
44  import org.apache.hc.core5.http.impl.Http1StreamListener;
45  import org.apache.hc.core5.http.impl.bootstrap.HttpRequester;
46  import org.apache.hc.core5.http.impl.bootstrap.RequesterBootstrap;
47  import org.apache.hc.core5.http.io.SocketConfig;
48  import org.apache.hc.core5.http.io.entity.EntityUtils;
49  import org.apache.hc.core5.http.io.entity.HttpEntities;
50  import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
51  import org.apache.hc.core5.http.message.BasicHeader;
52  import org.apache.hc.core5.http.message.RequestLine;
53  import org.apache.hc.core5.http.message.StatusLine;
54  import org.apache.hc.core5.http.protocol.HttpCoreContext;
55  import org.apache.hc.core5.io.IOCallback;
56  import org.apache.hc.core5.util.Timeout;
57  
58  /**
59   * Example of POST requests execution using classic I/O.
60   */
61  public class ClassicPostExecutionExample {
62  
63      public static void main(final String[] args) throws Exception {
64          final HttpRequester httpRequester = RequesterBootstrap.bootstrap()
65                  .setStreamListener(new Http1StreamListener() {
66  
67                      @Override
68                      public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
69                          System.out.println(connection.getRemoteAddress() + " " + new RequestLine(request));
70  
71                      }
72  
73                      @Override
74                      public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
75                          System.out.println(connection.getRemoteAddress() + " " + new StatusLine(response));
76                      }
77  
78                      @Override
79                      public void onExchangeComplete(final HttpConnection connection, final boolean keepAlive) {
80                          if (keepAlive) {
81                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection kept alive)");
82                          } else {
83                              System.out.println(connection.getRemoteAddress() + " exchange completed (connection closed)");
84                          }
85                      }
86  
87                  })
88                  .setSocketConfig(SocketConfig.custom()
89                          .setSoTimeout(5, TimeUnit.SECONDS)
90                          .build())
91                  .create();
92          final HttpCoreContext coreContext = HttpCoreContext.create();
93          final HttpHost target = new HttpHost("httpbin.org");
94  
95          final HttpEntity[] requestBodies = {
96                  HttpEntities.create(
97                          "This is the first test request",
98                          ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)),
99                  HttpEntities.create(
100                         "This is the second test request".getBytes(StandardCharsets.UTF_8),
101                         ContentType.APPLICATION_OCTET_STREAM),
102                 HttpEntities.create(new IOCallback<OutputStream>() {
103 
104                     @Override
105                     public void execute(final OutputStream outStream) throws IOException {
106                         outStream.write(("This is the third test request " +
107                                 "(streaming)").getBytes(StandardCharsets.UTF_8));
108                     }
109 
110                 }, ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)),
111                 HttpEntities.create(
112                         "This is the fourth test request " +
113                                 "(streaming with trailers)",
114                         ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8),
115                         new BasicHeader("trailer1","And goodbye"))
116         };
117 
118         final String requestUri = "/post";
119         for (int i = 0; i < requestBodies.length; i++) {
120             final ClassicHttpRequest request = new BasicClassicHttpRequest(Method.POST, target, requestUri);
121             request.setEntity(requestBodies[i]);
122             try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
123                 System.out.println(requestUri + "->" + response.getCode());
124                 System.out.println(EntityUtils.toString(response.getEntity()));
125                 System.out.println("==============");
126             }
127         }
128     }
129 
130 }