import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpUtils {
private static Log log = LogFactory.getLog(HttpUtils.class);
public static String doHttpGet(String strUrl){
String ret = "";
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(strUrl);
//以get方式请求
httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setConnectTimeout(30000);
httpurlconnection.setReadTimeout(30000);
httpurlconnection.setRequestMethod("GET");
//获取响应代码
int code = httpurlconnection.getResponseCode();
//log.info("code == " + code);
if(code == 200){
//获取页面内容
java.io.InputStream in = httpurlconnection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in , "UTF-8"));
String str=breader.readLine();
while(str != null){
ret += str;
str=breader.readLine();
}
}else{
ret="";
}
} catch(Exception e) {
log.info("webservice exception == " + e);
System.out.println("doHttpGet() error :"+e.getMessage());
} finally {
if(httpurlconnection!=null)
httpurlconnection.disconnect();
}
return ret;
}
public static String doHttpPost(String strUrl){
String ret = "";
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(strUrl.substring(0,strUrl.indexOf("?")));
//以post方式请求
httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setDoOutput(true);
httpurlconnection.setDoInput(true);
httpurlconnection.setConnectTimeout(30000);
httpurlconnection.setReadTimeout(30000);
httpurlconnection.setUseCaches(false);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.getOutputStream().write(strUrl.substring(strUrl.indexOf("?")+1, strUrl.length()).getBytes("UTF-8"));
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
//获取响应代码
int code = httpurlconnection.getResponseCode();
if(code == 200){
//获取页面内容
java.io.InputStream in = httpurlconnection.getInputStream();
java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in , "UTF-8"));
String str=breader.readLine();
while(str != null){
ret += str;
str=breader.readLine();
}
}else{
ret="";
}
} catch(Exception e) {
log.info("webservice exception == " + e);
System.out.println("doHttpPost() error :"+e.getMessage());
} finally {
if(httpurlconnection!=null)
httpurlconnection.disconnect();
}
return ret;
}
}