http请求工具类

import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpTools {

private HttpTools(){}

private static final Logger logger = Logger.getLogger(HttpTools.class);

public static String httpGet(String url,String charset){
logger.debug("发送 http get 请求 , URL : " + url);
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送GET请求出现异常!", e);
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
logger.error(e2.getMessage(),e2);
}
}
logger.debug("响应报文: " + result);
return result;
}

public static String httpGet(String url){
return httpGet(url,"UTF-8");
}

public static String httpPost(String url, String data){
return httpPost(url, data,"UTF-8");
}

public static String httpPost(String url, String data,String charset){
logger.debug("发送 http post 请求 , URL : " + url);
logger.debug("请求体: " + data);
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setDoOutput(true);
conn.setDoInput(true);
out = conn.getOutputStream();
out.write(data.getBytes(charset));
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!", e);
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
logger.error(ex.getMessage(),ex);
}
}
logger.debug("响应报文: " + result);
return result;
}

}
posted @ 2016-11-11 16:57  黄小易  阅读(459)  评论(0编辑  收藏  举报