java 原生 HttpClient

1package org.rx.socks.http; 2 3import com.google.common.base.Strings; 4import lombok.SneakyThrows; 5import org.rx.common.App; 6import org.rx.common.Contract; 7import org.rx.common.SystemException; 8import org.rx.socks.Sockets; 9import org.rx.io.IOStream; 10 11import java.io.UnsupportedEncodingException; 12import java.net.*; 13import java.util.LinkedHashMap; 14import java.util.Map; 15 16import static org.rx.common.Contract.eq; 17import static org.rx.common.Contract.isNull; 18 19/** 20 * http://www.jianshu.com/p/aa3f066263ed 21 */ 22public class HttpClient { 23 //region StaticMembers 24 @SneakyThrows 25 public static String urlEncode(String str) { 26 if (Strings.isNullOrEmpty(str)) { 27 return ""; 28 } 29 30 return URLEncoder.encode(str, Contract.Utf8).replace("+", "%20"); 31 } 32 33 public static Map<String, String> parseQueryString(String queryString) { 34 Map<String, String> map = new LinkedHashMap<>(); 35 if (queryString == null) { 36 return map; 37 } 38 39 String[] pairs = queryString.split("&"); 40 try { 41 for (String pair : pairs) { 42 int idx = pair.indexOf("="); 43 String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), Contract.Utf8) : pair; 44 String value = idx > 0 && pair.length() > idx + 1 45 ? URLDecoder.decode(pair.substring(idx + 1), Contract.Utf8) 46 : null; 47 map.put(key, value); 48 } 49 } catch (UnsupportedEncodingException ex) { 50 throw SystemException.wrap(ex); 51 } 52 return map; 53 } 54 55 public static String buildQueryString(String baseUrl, Map<String, String> params) { 56 if (params == null) { 57 return baseUrl; 58 } 59 if (baseUrl == null) { 60 baseUrl = ""; 61 } 62 63 String c = baseUrl.indexOf("?") == -1 ? "?" : "&"; 64 StringBuilder url = new StringBuilder(baseUrl); 65 for (String key : params.keySet()) { 66 String val = params.get(key); 67 url.append(url.length() == baseUrl.length() ? c : "&").append(urlEncode(key)).append("=") 68 .append(val == null ? "" : urlEncode(val)); 69 } 70 return url.toString(); 71 } 72 //endregion 73 74 public static final String GetMethod = "GET", PostMethod = "POST"; 75 private static final String FormMimeType = "application/x-www-form-urlencoded", JsonMimeType = "application/json"; 76 private static final String UserAgent = "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36"; 77 private String contentType; 78 private int timeout; 79 private String proxyHost; 80 81 public String getContentType() { 82 return contentType; 83 } 84 85 public void setContentType(String contentType) { 86 this.contentType = contentType; 87 } 88 89 public int getTimeout() { 90 return timeout; 91 } 92 93 public void setTimeout(int timeout) { 94 this.timeout = timeout; 95 } 96 97 public String getProxyHost() { 98 return proxyHost; 99 } 100 101 public void setProxyHost(String proxyHost) { 102 this.proxyHost = proxyHost; 103 } 104 105 public HttpClient() { 106 timeout = App.TimeoutInfinite; 107 } 108 109 public String httpGet(String url) { 110 return httpGet(url, null); 111 } 112 113 public String httpGet(String url, Map<String, String> params) { 114 if (params != null && params.size() > 0) { 115 url = buildQueryString(url, params); 116 } 117 return exec(url, GetMethod, null, contentType, timeout); 118 } 119 120 public String httpPost(String url, Map<String, String> params) { 121 contentType = FormMimeType; 122 return exec(url, PostMethod, buildQueryString("", params).substring(1), contentType, timeout); 123 } 124 125 public String httpPost(String url, Object jsonEntity) { 126 contentType = JsonMimeType; 127 return exec(url, PostMethod, Contract.toJsonString(jsonEntity), contentType, timeout); 128 } 129 130 private String exec(String url, String method, String content, String contentType, int timeout) { 131 String charset = Contract.Utf8; 132 try { 133 URL uri = new URL(url); 134 HttpURLConnection client = (HttpURLConnection) (proxyHost != null 135 ? uri.openConnection(new Proxy(Proxy.Type.HTTP, Sockets.parseAddress(proxyHost))) 136 : uri.openConnection()); 137 client.setDoOutput(true); 138 client.setDoInput(true); 139 client.setUseCaches(false); 140 client.setRequestProperty("User-Agent", UserAgent); 141 client.setRequestProperty("Accept-Charset", charset); 142 client.setRequestMethod(method); 143 if (!App.isNullOrEmpty(contentType)) { 144 client.setRequestProperty("Content-Type", contentType + ";charset=" + charset); 145 } 146 if (timeout > App.TimeoutInfinite) { 147 client.setConnectTimeout(timeout); 148 client.setReadTimeout(timeout); 149 } 150 client.connect(); 151 if (eq(method, PostMethod) && !App.isNullOrEmpty(content)) { 152 IOStream.writeString(client.getOutputStream(), content, charset); 153 } 154 155 int resCode = client.getResponseCode(); 156 if (resCode != HttpURLConnection.HTTP_OK) { 157 158 } 159 return IOStream.readString(client.getInputStream(), isNull(client.getContentEncoding(), charset)); 160 } catch (Exception ex) { 161 throw SystemException.wrap(ex); 162 } 163 } 164}

666   网购半价返利 http://f-li.cn

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )