工具方法总结
目录
1、读取配置文件 properties
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 读取配置文件 读取请求地址
* @author Administrator
*
*/
public class PropertiesReadUtil {
/**
* 读取配置文件
* @param param
* @param propertiesName
* @return
* 2018.11.1
*/
public static String readValue(String param,String propertiesName){
try {
Properties versionProperties = new Properties();
InputStream in = PropertiesReadUtil.class.getClassLoader().getResourceAsStream(propertiesName+".properties");
versionProperties.load(in);
return versionProperties.getProperty(param);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
2、构建URL地址
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
public class URLBuilderUtil {
private static boolean[] eucIgnore = new boolean[256];
protected StringBuilder builder = new StringBuilder();
protected boolean firstParam = true;
protected boolean hasPath = false;
private static String percentify(String s) {
StringBuilder sb = new StringBuilder();
ByteBuffer bb = Charset.forName("utf-8").encode(s);
int size = bb.limit();
for (int i = 0; i < size; i++) {
sb.append(String.format("%%%02x", new Object[] { Integer.valueOf(bb.get() & 0xFF) }));
}
return sb.toString();
}
public static String encodeURIComponent(String s) {
if (s == null) {
return null;
}
if ("".equals(s)) {
return "";
}
StringBuilder sb = new StringBuilder();
int _i = 0;
int c = Character.codePointAt(s, _i);
boolean ignore = (c < 256) && (eucIgnore[c]!=false);
for (int i = 0; i < s.length(); i++) {
c = Character.codePointAt(s, i);
if (ignore != ((c < 256) && (eucIgnore[c] != false))) {
if (ignore)
sb.append(s.substring(_i, i));
else
sb.append(percentify(s.substring(_i, i)));
ignore = !ignore;
_i = i;
}
}
if (ignore)
sb.append(s.substring(_i, s.length()));
else {
sb.append(percentify(s.substring(_i, s.length())));
}
return sb.toString();
}
protected void appendParamPrefix() {
if (this.firstParam) {
this.firstParam = false;
if (this.hasPath)
this.builder.append('?');
} else {
this.builder.append('&');
}
}
protected void appendParamPrefix_add() {
if (this.firstParam) {
this.firstParam = false;
if (this.hasPath)
this.builder.append('?');
} else {
this.builder.append('+');
}
}
public URLBuilderUtil appendPath(String path) {
if (path == null) {
return this;
}
if ((this.hasPath) || (!this.firstParam)) {
throw new IllegalStateException("Missed the trick to set path.");
}
this.hasPath = true;
this.builder.append(path);
return this;
}
public URLBuilderUtil appendParam(String key, Object value) {
if ((key != null) && (value != null)) {
appendParamPrefix();
this.builder.append(key).append('=');
this.builder.append(value);
}
return this;
}
public URLBuilderUtil appendParam(Object value) {
if (value != null) {
appendParamPrefix_add();
this.builder.append(value);
}
return this;
}
public URLBuilderUtil appendParamEncode(String key, String value) {
if ((key != null) && (value != null)) {
appendParamPrefix();
this.builder.append(key).append('=');
this.builder.append(encodeURIComponent(value));
}
return this;
}
public URLBuilderUtil appendParamEncode( String value) {
if (value != null) {
appendParamPrefix_add();
this.builder.append(encodeURIComponent(value));
}
return this;
}
public URLBuilderUtil appendParamEncode(String key, String charset ,String value) {
if (value != null) {
appendParamPrefix_add();
this.builder.append(key).append(charset);
this.builder.append(encodeURIComponent(value));
}
return this;
}
public URLBuilderUtil appendLabel(String label) {
this.builder.append('#').append(label);
return this;
}
public URLBuilderUtil append(String str) {
this.builder.append(str);
return this;
}
public String toString() {
return this.builder.toString();
}
static {
String ignore = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-_.!~*'()";
for (int i = 0; i < ignore.length(); i++)
eucIgnore[Character.codePointAt(ignore, i)] = true;
}
public static void main(String[] args){
URLBuilderUtil urlBuilder = new URLBuilderUtil();
urlBuilder.
appendPath("https://weixin.kaishustory.com").
appendParam("key1", "value1").
appendParam("key2", "value2").appendParamEncode("ekey3", "{$#你好}").appendLabel("label");
System.err.println(urlBuilder.toString());
}
}
3、将JSON串响应到客户端
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
/**
* 处理JSON
* @author huyande
*
*/
public class JsonUtils {
/**
* 将Json数据响应到客户端
* @param response
*/
public static void responseJson(HttpServletResponse response,String jsonString){
//以下代码从JSON.java中拷过来的
response.setContentType("text/html;charset=UTF-8");
PrintWriter out;
try {
out = response.getWriter();
out.println(jsonString);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4、使用HTTPClient 发送get/post 请求
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
/**
* 发送post / get 方法
* @author huyande
*
*/
public class HTTPClientUtils {
/**
* httpClient Post 方法
* @param url
* @param
* @return
* String ... queryString
*/
public static String requestPostJson(String url) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(20000).setSocketTimeout(20000)
.setConnectionRequestTimeout(20000)
.setStaleConnectionCheckEnabled(true).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig).build();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Connection", "close");
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity repEntity =null;
String content="";
try {
HttpResponse response = httpClient.execute(httpPost);
System.out.println(response.getAllHeaders());
repEntity=response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
content = EntityUtils.toString(repEntity);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HttpGet Method failed: "
+ response.getStatusLine());
return null;
}
} catch (Exception e1) {
// log.error(e1.getMessage());
e1.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return content;
}
/**
* Httpclient get请求
* @param url
* @return
*/
public static String requestGetJson(String url) {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(20000).setSocketTimeout(20000)
.setConnectionRequestTimeout(20000)
.setStaleConnectionCheckEnabled(true).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(defaultRequestConfig).build();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Connection", "close");
httpGet.setHeader("Content-Type", "application/json; charset=utf-8");
HttpEntity repEntity =null;
String content="";
try {
HttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getAllHeaders());
repEntity=response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
content = EntityUtils.toString(repEntity);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HttpGet Method failed: "
+ response.getStatusLine());
return null;
}
} catch (Exception e1) {
// log.error(e1.getMessage());
e1.printStackTrace();
} finally {
httpGet.releaseConnection();
}
return content;
}
}