码迷,mamicode.com
首页 > Web开发 > 详细

http请求工具类

时间:2016-11-11 17:18:37      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:报文   apache   http请求   name   stat   sage   class   tin   响应报文   

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请求工具类

标签:报文   apache   http请求   name   stat   sage   class   tin   响应报文   

原文地址:http://www.cnblogs.com/hjy1017/p/6054886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!