http请求工具类
Posted 黄小易
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
}
以上是关于http请求工具类的主要内容,如果未能解决你的问题,请参考以下文章