/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao (cnfree2000@hotmail.com) ***/
package com.ods.common.util;
import com.ods.common.util.MyFile;
import com.ods.common.util.PropUtil;
import com.ods.common.util.ProxyUtil;
import com.ods.common.util.StringUtil;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.springframework.http.HttpStatus;
public class HttpUtil {
private static Logger logger = LogManager.getLogger(HttpUtil.class.getName());
public static void main(String[] args) throws Exception {
String content = "111";
String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";
String qw = sendGet(url);
JSONObject object = JSONObject.fromObject(qw);
System.out.println(object);
}
@Test
public void name() {
String points_date = "2015-12-05 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = sdf.parse(points_date);
} catch (ParseException arg4) {
arg4.printStackTrace();
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
points_date = format.format(date);
System.out.println(points_date);
}
public static JSONObject postMap(String url, Map<String, Object> headerMap, Map<String, Object> paramMap, String stringType) throws IOException {
CloseableHttpClient httpclient = null;
JSONObject responseJson = null;
String ifproxy = PropUtil.getPropertyValue("ods.http.is.proxy", "0").replace("\"", "");
if(!"0".equals(ifproxy)) {
String postMethod = PropUtil.getPropertyValue("ods.http.proxy.server", "10.74.46.189:8080").replace("\"", "");
String requestConfig = PropUtil.getPropertyValue("ods.http.proxy.not", "127.0.0.1").replace("\"", "");
String[] hashMap = postMethod.split(":");
String e = hashMap[0];
boolean result = false;
String[] entity = requestConfig.split(",");
int proxyPort;
for(proxyPort = 0; proxyPort < entity.length; ++proxyPort) {
if(url.indexOf(entity[proxyPort]) >= 0) {
httpclient = HttpClients.custom().build();
result = true;
break;
}
}
if(!result) {
proxyPort = Integer.valueOf(hashMap[1]).intValue();
HttpHost proxy = new HttpHost(e, proxyPort);
httpclient = HttpClients.custom().setProxy(proxy).build();
}
} else {
httpclient = HttpClients.custom().build();
}
HttpPost arg18 = new HttpPost(url);
if(StringUtil.isNotEmpty(headerMap)) {
Iterator arg19 = headerMap.entrySet().iterator();
while(arg19.hasNext()) {
Entry arg21 = (Entry)arg19.next();
arg18.setHeader((String)arg21.getKey(), (String)arg21.getValue());
}
}
RequestConfig arg20 = RequestConfig.custom().setSocketTimeout('').setConnectTimeout('').build();
new HashMap();
try {
arg18.setConfig(arg20);
if("json".equals(stringType)) {
if(StringUtil.isNotEmpty(paramMap)) {
StringEntity arg23 = new StringEntity(JSONObject.fromObject(paramMap).toString(), "utf-8");
arg23.setContentEncoding("utf-8");
arg23.setContentType("application/json");
arg18.setEntity(arg23);
}
} else {
ArrayList arg22 = new ArrayList();
if(StringUtil.isNotEmpty(paramMap)) {
Iterator arg25 = paramMap.entrySet().iterator();
while(arg25.hasNext()) {
Entry arg27 = (Entry)arg25.next();
arg22.add(new BasicNameValuePair((String)arg27.getKey(), (String)arg27.getValue()));
}
UrlEncodedFormEntity arg28 = new UrlEncodedFormEntity(arg22, "UTF-8");
arg18.setEntity(arg28);
}
}
CloseableHttpResponse arg24 = httpclient.execute(arg18);
if(arg24.getStatusLine().getStatusCode() == HttpStatus.OK.value() || arg24.getStatusLine().getStatusCode() == HttpStatus.ACCEPTED.value() || arg24.getStatusLine().getStatusCode() == HttpStatus.UNAUTHORIZED.value()) {
String arg26 = EntityUtils.toString(arg24.getEntity(), "utf-8");
responseJson = JSONObject.fromObject(arg26);
}
} catch (IOException arg16) {
arg16.printStackTrace();
logger.error("postMap请求出现异常,url:" + url + arg16);
} finally {
httpclient.close();
}
return responseJson;
}
public static String Post(String url, String param) throws Exception {
Object in = null;
String result = "";
DataOutputStream out = null;
try {
URL e = new URL(url);
Proxy proxy = ProxyUtil.getHttpProxy(url);
HttpURLConnection connection = null;
if(proxy == null) {
connection = (HttpURLConnection)e.openConnection();
} else {
connection = (HttpURLConnection)e.openConnection(proxy);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setReadTimeout(300000);
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
out.write(param.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sbf = new StringBuffer();
String lines;
while((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbf.append(lines);
}
result = sbf.toString();
reader.close();
connection.disconnect();
} catch (ConnectException arg20) {
logger.error("Post请求出现异常:连接超时,url:" + url + arg20);
} catch (Exception arg21) {
logger.error("Post请求出现异常,url:" + url + arg21);
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
((BufferedReader)in).close();
}
} catch (IOException arg19) {
arg19.printStackTrace();
}
}
return result;
}
public static String Post(String url, String param, String charsetname) throws Exception {
if(StringUtil.isNotEmpty(charsetname)) {
charsetname = "UTF-8";
}
Object in = null;
String result = "";
DataOutputStream out = null;
try {
URL e = new URL(url);
Proxy proxy = ProxyUtil.getHttpProxy(url);
HttpURLConnection connection = null;
if(proxy == null) {
connection = (HttpURLConnection)e.openConnection();
} else {
connection = (HttpURLConnection)e.openConnection(proxy);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charsetname);
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
out.write(param.getBytes(charsetname));
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charsetname));
StringBuffer sbf = new StringBuffer();
String lines;
while((lines = reader.readLine()) != null) {
String iso = new String(lines.getBytes("UTF-8"), "ISO-8859-1");
lines = new String(iso.getBytes("ISO-8859-1"), "UTF-8");
String iso1 = new String(lines.getBytes("gbk"), "ISO-8859-1");
String lines1 = new String(iso1.getBytes("ISO-8859-1"), "gbk");
logger.error("GB2312:" + Charset.forName("GB2312").newEncoder().canEncode(lines));
logger.error("ISO-8859-1:" + Charset.forName("ISO-8859-1").newEncoder().canEncode(lines));
logger.error("gbk:" + Charset.forName("gbk").newEncoder().canEncode(lines));
logger.error("utf-8:" + Charset.forName("utf-8").newEncoder().canEncode(lines));
sbf.append(lines);
logger.error("lines:" + lines);
logger.error("lines1:" + lines1);
}
result = sbf.toString();
reader.close();
connection.disconnect();
} catch (ConnectException arg24) {
logger.error("Post请求出现异常:连接超时,url:" + url + arg24);
} catch (Exception arg25) {
logger.error("Post请求出现异常,url:" + url + arg25);
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
((BufferedReader)in).close();
}
} catch (IOException arg23) {
arg23.printStackTrace();
}
}
return result;
}
public static String Post(String url, String postData, Map<String, String> headers) throws IOException {
URL u = null;
HttpURLConnection con = null;
InputStream inputStream = null;
OutputStreamWriter outStream = null;
ByteArrayOutputStream baos = null;
String result = null;
try {
u = new URL(url);
con = (HttpURLConnection)u.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if(headers != null && !headers.isEmpty()) {
Iterator arg9 = headers.keySet().iterator();
while(arg9.hasNext()) {
String e = (String)arg9.next();
con.setRequestProperty(e, (String)headers.get(e));
}
}
outStream = new OutputStreamWriter(con.getOutputStream());
outStream.write(postData);
outStream.flush();
outStream.close();
if(con.getResponseCode() == 200) {
inputStream = con.getInputStream();
baos = new ByteArrayOutputStream();
boolean e1 = true;
int e2;
while((e2 = inputStream.read()) != -1) {
baos.write(e2);
}
result = baos.toString("utf-8");
} else {
logger.error("请求返回错误码:" + con.getResponseCode());
}
} catch (Exception arg13) {
arg13.printStackTrace();
} finally {
if(con != null) {
con.disconnect();
}
if(inputStream != null) {
inputStream.close();
}
if(outStream != null) {
outStream.close();
}
if(baos != null) {
baos.close();
}
}
return result;
}
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
HttpURLConnection conn = null;
try {
URL realUrl = new URL(url);
Proxy proxy = ProxyUtil.getHttpProxy(url);
if(proxy == null) {
conn = (HttpURLConnection)realUrl.openConnection();
} else {
conn = (HttpURLConnection)realUrl.openConnection(proxy);
}
conn.setRequestProperty("accept", "**");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("contentType", "UTF-8");
outputStream = conn.getOutputStream();
outputStream.write(param.getBytes("UTF-8"));
outputStream.flush();
String line;
for(in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); (line = in.readLine()) != null; result = result + "\n" + line) {
;
}
} catch (ConnectException arg23) {
logger.error("sendPost请求出现异常:连接超时" + url + arg23);
} catch (Exception arg24) {
logger.error("sendPost请求出现异常,url:" + url + arg24);
} finally {
if(conn != null) {
conn.disconnect();
}
try {
if(in != null) {
in.close();
}
} catch (IOException arg22) {
arg22.printStackTrace();
}
try {
if(outputStream != null) {
outputStream.close();
}
} catch (IOException arg21) {
arg21.printStackTrace();
}
}
return result;
}
public static JSONObject uploadMedia(String Url, String filePath) {
JSONObject jsonObj = null;
BufferedReader reader = null;
try {
URL e = new URL(Url);
String result = null;
File file = new File(filePath);
if(!file.exists() || !file.isFile()) {
throw new IOException("上传的文件不存在");
}
Proxy proxy = ProxyUtil.getHttpProxy(Url);
HttpURLConnection conn = null;
if(proxy == null) {
conn = (HttpURLConnection)e.openConnection();
} else {
conn = (HttpURLConnection)e.openConnection(proxy);
}
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(new FileInputStream(file));
boolean bytes = false;
byte[] bufferOut = new byte[1024];
int bytes1;
while((bytes1 = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes1);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
if(result == null) {
result = buffer.toString();
}
jsonObj = JSONObject.fromObject(result);
} catch (ConnectException arg28) {
logger.error("uploadMedia请求出现异常:连接超时,url:" + Url + arg28);
} catch (Exception arg29) {
logger.error("uploadMedia请求出现异常,url:" + Url + arg29);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException arg27) {
arg27.printStackTrace();
}
}
}
return jsonObj;
}
public static MyFile downloadMedia(String url) {
Object bis = null;
MyFile mf = new MyFile();
try {
URL e = new URL(url);
Proxy proxy = ProxyUtil.getHttpProxy(url);
HttpURLConnection conn = null;
if(proxy == null) {
conn = (HttpURLConnection)e.openConnection();
} else {
conn = (HttpURLConnection)e.openConnection(proxy);
}
conn.setDoInput(true);
conn.setRequestMethod("GET");
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
conn.connect();
String fileExt = conn.getHeaderField("Content-Type");
fileExt = getFileExt(fileExt);
UUID uuid = UUID.randomUUID();
InputStream is = conn.getInputStream();
mf.setFileName(uuid + fileExt);
mf.setInStream(is);
conn.disconnect();
} catch (ConnectException arg8) {
logger.error("downloadMedia请求出现异常:连接超时,url:" + url + arg8);
} catch (Exception arg9) {
logger.error("downloadMedia请求出现异常,url:" + url + arg9);
}
return mf;
}
public static String uploadByUrlInputream(InputStream inputStream, String fileName, String surl) {
BufferedReader reader = null;
String result = null;
try {
URL e = new URL(surl);
Proxy proxy = ProxyUtil.getHttpProxy(surl);
HttpURLConnection con = null;
if(proxy == null) {
con = (HttpURLConnection)e.openConnection();
} else {
con = (HttpURLConnection)e.openConnection(proxy);
}
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(inputStream);
boolean bytes = false;
byte[] bufferOut = new byte[1024];
int bytes1;
while((bytes1 = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes1);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
if(result == null) {
result = buffer.toString();
}
} catch (ConnectException arg27) {
logger.error("uploadByUrlInputream请求出现异常:连接超时,url:" + surl + arg27);
} catch (Exception arg28) {
logger.error("uploadByUrlInputream请求出现异常,url:" + surl + arg28);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException arg26) {
arg26.printStackTrace();
}
}
}
return result;
}
public static String uploadByInputream(FileInputStream fileStream, String fileName, String surl) {
BufferedReader reader = null;
String result = null;
try {
URL e = new URL(surl);
Proxy proxy = ProxyUtil.getHttpProxy(surl);
HttpURLConnection con = null;
if(proxy == null) {
con = (HttpURLConnection)e.openConnection();
} else {
con = (HttpURLConnection)e.openConnection(proxy);
}
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(fileStream);
boolean bytes = false;
byte[] bufferOut = new byte[1024];
int bytes1;
while((bytes1 = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes1);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
if(result == null) {
result = buffer.toString();
}
} catch (ConnectException arg27) {
logger.error("uploadByInputream请求出现异常:连接超时,url:" + surl + arg27);
} catch (Exception arg28) {
logger.error("uploadByInputream请求出现异常,url:" + surl + arg28);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException arg26) {
arg26.printStackTrace();
}
}
}
return result;
}
public static String uploadByInputream(InputStream fileStream, String fileName, String surl) {
BufferedReader reader = null;
String result = null;
try {
URL e = new URL(surl);
Proxy proxy = ProxyUtil.getHttpProxy(surl);
HttpURLConnection con = null;
if(proxy == null) {
con = (HttpURLConnection)e.openConnection();
} else {
con = (HttpURLConnection)e.openConnection(proxy);
}
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
DataInputStream in = new DataInputStream(fileStream);
boolean bytes = false;
byte[] bufferOut = new byte[1024];
int bytes1;
while((bytes1 = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes1);
}
in.close();
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
buffer.append(line);
}
if(result == null) {
result = buffer.toString();
}
} catch (ConnectException arg27) {
logger.error("uploadByInputream请求出现异常:连接超时,url:" + surl + arg27);
} catch (Exception arg28) {
logger.error("uploadByInputream请求出现异常,url:" + surl + arg28);
} finally {
if(reader != null) {
try {
reader.close();
} catch (IOException arg26) {
arg26.printStackTrace();
}
}
}
return result;
}
public static String getFileExt(String contentType) {
String fileExt = "";
if(!"image/jpeg".equals(contentType) && !"image/jpg".equals(contentType)) {
if("image/png".equals(contentType)) {
fileExt = ".png";
} else if("audio/mpeg".equals(contentType)) {
fileExt = ".mp3";
} else if("audio/amr".equals(contentType)) {
fileExt = ".amr";
} else if("video/mp4".equals(contentType)) {
fileExt = ".mp4";
} else if("video/mpeg4".equals(contentType)) {
fileExt = ".mp4";
}
} else {
fileExt = ".jpg";
}
return fileExt;
}
}
作者:候鸟 出处:http://www.cnblogs.com/swite/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |