package org.rx.socks.http;

import com.google.common.base.Strings;
import lombok.SneakyThrows;
import org.rx.common.App;
import org.rx.common.Contract;
import org.rx.common.SystemException;
import org.rx.socks.Sockets;
import org.rx.io.IOStream; import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.LinkedHashMap;
import java.util.Map; import static org.rx.common.Contract.eq;
import static org.rx.common.Contract.isNull; /**
* http://www.jianshu.com/p/aa3f066263ed
*/
public class HttpClient {
//region StaticMembers
@SneakyThrows
public static String urlEncode(String str) {
if (Strings.isNullOrEmpty(str)) {
return "";
} return URLEncoder.encode(str, Contract.Utf8).replace("+", "%20");
} public static Map<String, String> parseQueryString(String queryString) {
Map<String, String> map = new LinkedHashMap<>();
if (queryString == null) {
return map;
} String[] pairs = queryString.split("&");
try {
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), Contract.Utf8) : pair;
String value = idx > 0 && pair.length() > idx + 1
? URLDecoder.decode(pair.substring(idx + 1), Contract.Utf8)
: null;
map.put(key, value);
}
} catch (UnsupportedEncodingException ex) {
throw SystemException.wrap(ex);
}
return map;
} public static String buildQueryString(String baseUrl, Map<String, String> params) {
if (params == null) {
return baseUrl;
}
if (baseUrl == null) {
baseUrl = "";
} String c = baseUrl.indexOf("?") == -1 ? "?" : "&";
StringBuilder url = new StringBuilder(baseUrl);
for (String key : params.keySet()) {
String val = params.get(key);
url.append(url.length() == baseUrl.length() ? c : "&").append(urlEncode(key)).append("=")
.append(val == null ? "" : urlEncode(val));
}
return url.toString();
}
//endregion public static final String GetMethod = "GET", PostMethod = "POST";
private static final String FormMimeType = "application/x-www-form-urlencoded", JsonMimeType = "application/json";
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";
private String contentType;
private int timeout;
private String proxyHost; public String getContentType() {
return contentType;
} public void setContentType(String contentType) {
this.contentType = contentType;
} public int getTimeout() {
return timeout;
} public void setTimeout(int timeout) {
this.timeout = timeout;
} public String getProxyHost() {
return proxyHost;
} public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
} public HttpClient() {
timeout = App.TimeoutInfinite;
} public String httpGet(String url) {
return httpGet(url, null);
} public String httpGet(String url, Map<String, String> params) {
if (params != null && params.size() > 0) {
url = buildQueryString(url, params);
}
return exec(url, GetMethod, null, contentType, timeout);
} public String httpPost(String url, Map<String, String> params) {
contentType = FormMimeType;
return exec(url, PostMethod, buildQueryString("", params).substring(1), contentType, timeout);
} public String httpPost(String url, Object jsonEntity) {
contentType = JsonMimeType;
return exec(url, PostMethod, Contract.toJsonString(jsonEntity), contentType, timeout);
} private String exec(String url, String method, String content, String contentType, int timeout) {
String charset = Contract.Utf8;
try {
URL uri = new URL(url);
HttpURLConnection client = (HttpURLConnection) (proxyHost != null
? uri.openConnection(new Proxy(Proxy.Type.HTTP, Sockets.parseAddress(proxyHost)))
: uri.openConnection());
client.setDoOutput(true);
client.setDoInput(true);
client.setUseCaches(false);
client.setRequestProperty("User-Agent", UserAgent);
client.setRequestProperty("Accept-Charset", charset);
client.setRequestMethod(method);
if (!App.isNullOrEmpty(contentType)) {
client.setRequestProperty("Content-Type", contentType + ";charset=" + charset);
}
if (timeout > App.TimeoutInfinite) {
client.setConnectTimeout(timeout);
client.setReadTimeout(timeout);
}
client.connect();
if (eq(method, PostMethod) && !App.isNullOrEmpty(content)) {
IOStream.writeString(client.getOutputStream(), content, charset);
} int resCode = client.getResponseCode();
if (resCode != HttpURLConnection.HTTP_OK) { }
return IOStream.readString(client.getInputStream(), isNull(client.getContentEncoding(), charset));
} catch (Exception ex) {
throw SystemException.wrap(ex);
}
}
}

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

java 原生 HttpClient的更多相关文章

  1. 使用Java原生代理实现AOP

    ### 本文由博主柒.原创,转载请注明出处 ### 完整源码下载地址 [https://github.com/MatrixSeven/JavaAOP](https://github.com/Matri ...

  2. Java通过httpclient获取cookie模拟登录

    package Step1; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Htt ...

  3. android 学习随笔二十七(JNI:Java Native Interface,JAVA原生接口 )

    JNI(Java Native Interface,JAVA原生接口) 使用JNI可以使Java代码和其他语言写的代码(如C/C++代码)进行交互. 问:为什么要进行交互? 首先,Java语言提供的类 ...

  4. 【Java】Java原生的序列化和反序列化

    写一个Java原生的序列化和反序列化的DEMO. 需序列化的类: package com.nicchagil.nativeserialize; import java.io.Serializable; ...

  5. 使用Java原生代理实现数据注入

    本文由博主原创,转载请注明出处 完整源码下载地址 https://github.com/MatrixSeven/JavaAOP 上一篇,咱们说了使用Java原生代理实现AOP的简单例子,然么就不得不说 ...

  6. Java中httpClient中三种超时设置

    本文章给大家介绍一下关于Java中httpClient中的三种超时设置小结 在Apache的HttpClient包中,有三个设置超时的地方: /* 从连接池中取连接的超时时间*/ ConnManage ...

  7. 分布式架构探索 - 1. RPC框架之Java原生RMI

    1. 什么是RPC RPC(Remote Procedure Call)即远程过程调用,指的是不同机器间系统方法的调用,这和 同机器动态链接库(DLL)有点类似,只不过RPC是不同机器,通过网络通信来 ...

  8. Java使用HttpClient上传文件

    Java可以使用HttpClient发送Http请求.上传文件等,非常的方便 Maven <dependency> <groupId>org.apache.httpcompon ...

  9. java使用HttpClient

    HttpClient常用的包有两个 org.apache.http.client以及org.apache.commons.httpclient 我常用的是org.apache.http.client. ...

随机推荐

  1. ZROI week5

    考试 Part 简单题,从结尾倒着扫一遍就行. Pref 选一个最长的好的序列. 题目有点小简单,似乎直接哈希就行,然后还打了一遍\(kmp\). Chess 一道很不错的题目,用异或维护修改即可. ...

  2. C++笔试题之宏定义相关

    1. #define CALC(X) X*X int i; i=CALC(+)/(+); cout<<i<<endl; 输出:31 宏定义在替换处展开为:i = 5+5*5+5 ...

  3. Celery 'Getting Started' not able to retrieve results; always pending

    参考 根据Celery的官方文档,当使用windows 10 64-bit, Python 2.7,Erlang 64-bit binary, RabbitMQ server and celery r ...

  4. 后台date类型转换为json字符串时,返回前台页面的是long类型的时间戳问题解决

    学习springboot框架,写个博客系统,在后台管理的日志管理中,遇到了后台查询的日期格式的结果返回到页面变成了日期的时间戳了.然后摸索了三种方法来解决.页面的显示问题如下图. 问题页面回顾: 本案 ...

  5. PAT甲级——A1153 DecodeRegistrationCardofPAT【25】

    A registration card number of PAT consists of 4 parts: the 1st letter represents the test level, nam ...

  6. 哈希表(hash)详解

     哈希表结构讲解: 哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构.也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度. ...

  7. log4j日志记录到数据库

    log4j API提供 org.apache.log4j.jdbc.JDBCAppender 对象,它能够将日志信息在指定的数据库. JDBCAppender 配置: Property 描述 buff ...

  8. mysql的时间存储格式

    虽然mysql提供了datatime和timestamp两种存储时间的格式,但是如果设计较多计算,应存INT(11)类型.

  9. 学习JS基本数据类型与对象的valueOf方法

    https://blog.csdn.net/licheng11403080324/article/details/60128090 https://yq.aliyun.com/articles/399 ...

  10. LeetCode Array Easy 167. Two Sum II - Input array is sorted

    Description Given an array of integers that is already sorted in ascending order, find two numbers s ...