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.http.examples.fluent; 28 29 import java.io.File; 30 31 import org.apache.hc.client5.http.fluent.Form; 32 import org.apache.hc.client5.http.fluent.Request; 33 import org.apache.hc.core5.http.ContentType; 34 import org.apache.hc.core5.http.HttpHost; 35 import org.apache.hc.core5.http.HttpVersion; 36 import org.apache.hc.core5.util.Timeout; 37 38 /** 39 * This example demonstrates basics of request execution with the HttpClient fluent API. 40 */ 41 public class FluentRequests { 42 43 public static void main(final String... args)throws Exception { 44 // Execute a GET with timeout settings and return response content as String. 45 Request.get("http://somehost/") 46 .connectTimeout(Timeout.ofSeconds(1)) 47 .responseTimeout(Timeout.ofSeconds(5)) 48 .execute().returnContent().asString(); 49 50 // Execute a POST with the 'expect-continue' handshake, using HTTP/1.1, 51 // containing a request body as String and return response content as byte array. 52 Request.post("http://somehost/do-stuff") 53 .useExpectContinue() 54 .version(HttpVersion.HTTP_1_1) 55 .bodyString("Important stuff", ContentType.DEFAULT_TEXT) 56 .execute().returnContent().asBytes(); 57 58 // Execute a POST with a custom header through the proxy containing a request body 59 // as an HTML form and save the result to the file 60 Request.post("http://somehost/some-form") 61 .addHeader("X-Custom-header", "stuff") 62 .viaProxy(new HttpHost("myproxy", 8080)) 63 .bodyForm(Form.form().add("username", "vip").add("password", "secret").build()) 64 .execute().saveContent(new File("result.dump")); 65 } 66 67 }