public static String httpPost(String source, String params) {
URL url = null;
HttpURLConnection conn = null;
OutputStream os = null;
String ret = null;
try {
url = new URL(source);
conn = (HttpURLConnection) url.openConnection();
addRequestHeader(conn);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
if (params != null) {
os = conn.getOutputStream();
os.write(params.getBytes("UTF-8"));
os.flush();
}
InputStream is = conn.getInputStream();
ret = getResponse(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
return ret;
}
public static String httpGet(String source) {
URL url = null;
HttpURLConnection conn = null;
String ret = null;
try {
url = new URL(source);
conn = (HttpURLConnection) url.openConnection();
addRequestHeader(conn);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
InputStream is = conn.getInputStream();
ret = getResponse(is);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return ret;
}
public static String getResponse(InputStream is) {
GZIPInputStream gzip = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String ret = null;
try {
gzip = new GZIPInputStream(is);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = gzip.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.flush();
ret = new String(baos.toByteArray(), "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.close();
}
if (gzip != null) {
gzip.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ret;
}
public static void addRequestHeader(HttpURLConnection conn) {
conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8");
conn.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1;q=0.5");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
}