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. AcWing 230. 排列计数 水题(组合数+错排)打卡

    题目:https://www.acwing.com/problem/content/232/ #include<bits/stdc++.h> #define ll long long #d ...

  2. 为何使用Html5+CSS3

    一:大多浏览器支持,低版本也没问题 我看点这方面的资料,是为了做手机应用网站(有三个方案,这个是备用方案),可以开发响应式网站,可以脱离开发平台进行跨平台. 在Html5网页中引入Modernizr, ...

  3. setTag()与getTag()的使用介绍

    转载博客:http://www.cnblogs.com/topcoderliu/archive/2011/06/07/2074419.html View中的setTag(Onbect)表示给View添 ...

  4. MySQL导入导出数据和表结构 source和mysqldump

    MySQL导入数据的方式: 1.使用source /dir/test.sql导入数据进入数据库:查询数据库编码格式show variables like "%char%";设置编码 ...

  5. 使用java读取excel数据

    package excelOperation2; import java.io.File; import java.io.FileNotFoundException; import java.util ...

  6. 【Vue】---Vue.config常用配置项

    一.前言 Vue-cli3 搭建的项目 相比较Vue-cli2界面相对较为简洁,之前的build和config文件夹不见了,那么应该如何配置 如webpack等的配呢? 二.基本配置 只需要在项目的根 ...

  7. Apache 2.4.12 64位+Tomcat-8.0.32-windows-x64负载集群方案

    上次搞了Apache 2.2的集群方案,但是现在自己的机器和客户的服务器一般都是64位的,而且tomcat已经到8了.重新做Apache 2.4.12 64位+Tomcat-8.0.32-window ...

  8. 厉害了,Spring团队又开源 nohttp 项目!

    作者:h4cd 来源:https://www.oschina.net/news/107377/spring-opensource-nohttp Spring 团队开源 nohttp 项目,用以查找.替 ...

  9. redis的快速机制与数据类型

    想一下 redis 的高并发和快速 单线程模型 - 避免了不必要的上下文切换和竞争条件(锁) Redis客户端对服务端的每次调用都经历了发送命令,执行命令,返回结果三个过程.其中执行命令阶段,由于Re ...

  10. Vue--入门篇

    一.v-model和单选按钮(radio) <div id="app"> <input name="sex" value="男&qu ...