使用简单介绍 @author arron @date 2016年11月7日 下午2:36:16 @version 1.0
| 22 | * @version 1.0 |
| 23 | */ |
| 24 | public class Demo { |
| 25 | |
| 26 | public static void main(String[] args) throws HttpProcessException, FileNotFoundException { |
| 27 | String url = "https://github.com/Arronlong/httpclientutil"; |
| 28 | |
| 29 | //最简单的使用: |
| 30 | String html = HttpClientUtil.get(HttpConfig.custom().url(url)); |
| 31 | System.out.println(html); |
| 32 | |
| 33 | //--------------------------------- |
| 34 | // 【详细说明】 |
| 35 | //-------------------------------- |
| 36 | |
| 37 | //插件式配置Header(各种header信息、自定义header) |
| 38 | Header[] headers = HttpHeader.custom() |
| 39 | .userAgent("javacl") |
| 40 | .other("customer", "自定义") |
| 41 | .build(); |
| 42 | |
| 43 | //插件式配置生成HttpClient时所需参数(超时、连接池、ssl、重试) |
| 44 | HCB hcb = HCB.custom() |
| 45 | .timeout(1000) //超时 |
| 46 | .pool(100, 10) //启用连接池,每个路由最大创建10个链接,总连接数限制为100个 |
| 47 | .sslpv(SSLProtocolVersion.TLSv1_2) //可设置ssl版本号,默认SSLv3,用于ssl,也可以调用sslpv("TLSv1.2") |
| 48 | .ssl() //https,支持自定义ssl证书路径和密码,ssl(String keyStorePath, String keyStorepass) |
| 49 | .retry(5) //重试5次 |
| 50 | ; |
| 51 | |
| 52 | HttpClient client = hcb.build(); |
| 53 | |
| 54 | Map<String, Object> map = new HashMap<String, Object>(); |
| 55 | map.put("key1", "value1"); |
| 56 | map.put("key2", "value2"); |
| 57 | |
| 58 | //插件式配置请求参数(网址、请求参数、编码、client) |
| 59 | HttpConfig config = HttpConfig.custom() |
| 60 | .headers(headers) //设置headers,不需要时则无需设置 |
| 61 | .url(url) //设置请求的url |
| 62 | .map(map) //设置请求参数,没有则无需设置 |
| 63 | .encoding("utf-8") //设置请求和返回编码,默认就是Charset.defaultCharset() |
| 64 | //.client(client) //如果只是简单使用,无需设置,会自动获取默认的一个client对象 |
| 65 | //.inenc("utf-8") //设置请求编码,如果请求返回一直,不需要再单独设置 |
| 66 | //.inenc("utf-8") //设置返回编码,如果请求返回一直,不需要再单独设置 |
| 67 | //.json("json字符串") //json方式请求的话,就不用设置map方法,当然二者可以共用。 |
| 68 | //.context(HttpCookies.custom().getContext()) //设置cookie,用于完成携带cookie的操作 |
| 69 | //.out(new FileOutputStream("保存地址")) //下载的话,设置这个方法,否则不要设置 |
| 70 | //.files(new String[]{"d:/1.txt","d:/2.txt"}) //上传的话,传递文件路径,一般还需map配置,设置服务器保存路径 |
| 71 | ; |
| 72 | |
| 73 | |
| 74 | //使用方式: |
| 75 | String result1 = HttpClientUtil.get(config); //get请求 |
| 76 | String result2 = HttpClientUtil.post(config); //post请求 |
| 77 | System.out.println(result1); |
| 78 | System.out.println(result2); |
| 79 | |
| 80 | //HttpClientUtil.down(config); //下载,需要调用config.out(fileOutputStream对象) |
| 81 | //HttpClientUtil.upload(config); //上传,需要调用config.files(文件路径数组) |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…