package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* url请求方法
* @param urlStr url字符串
* @param timeout 超时时间
* @param sign 检测字符串
* @return 如果url返回结果包含sign且不超时,则返回true,否则返回false
*/
public static boolean webgetForCheck(String urlStr,int timeout,String sign){
try{
String content=webget(urlStr,timeout);
if(StringUtils.isNotBlank(content)){
return StringUtils.containsIgnoreCase(content, sign);
}else if(StringUtils.isBlank(sign) && StringUtils.isBlank(content)){
return true;
}
}catch(Exception e){
log.error("webgetForCheck方法执行出现异常!",e);
}
return false;
}
/**
* url请求
* @param urlStr
* @param timeout
* @return
* @throws IOException
*/
public static String webget(String urlStr, int timeout) throws IOException {
HttpURLConnection conn = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = "";
while ((temp=reader.readLine())!=null) {
sb.append(temp).append("\n");
}
/*int ch = is.read();
while (ch != -1) {
sb.append((char) ch);
ch = is.read();
}*/
} catch (IOException e) {
log.error("在访问链接"+urlStr+"时,出现异常!",e);
e = new IOException("1");
throw e;
} finally {
if (conn != null) {
conn.disconnect();
}
try {
if (null != is)
is.close();
} catch (IOException e) {
e = new IOException("2");
throw e;
}
}
return sb.toString().trim();
}
/**
* 发送带有表单参数的POST请求
*
* @param requestUrl 请求的地址(不含参数)
* @return 响应内容
*/
@SuppressWarnings({ "finally", "unused" })
public static String sendPostRequest(String requestUrl,String[] param,String[] values) {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
HttpPost httpPost = new HttpPost(requestUrl); // 创建HttpPost
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
for(int i =0;i<param.length;i++){
String p = param[i];
String v = values[i];
formParams.add(new BasicNameValuePair(p,v));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost); // 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); // Consume response content
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
return responseContent;
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* url请求方法
* @param urlStr url字符串
* @param timeout 超时时间
* @param sign 检测字符串
* @return 如果url返回结果包含sign且不超时,则返回true,否则返回false
*/
public static boolean webgetForCheck(String urlStr,int timeout,String sign){
try{
String content=webget(urlStr,timeout);
if(StringUtils.isNotBlank(content)){
return StringUtils.containsIgnoreCase(content, sign);
}else if(StringUtils.isBlank(sign) && StringUtils.isBlank(content)){
return true;
}
}catch(Exception e){
log.error("webgetForCheck方法执行出现异常!",e);
}
return false;
}
/**
* url请求
* @param urlStr
* @param timeout
* @return
* @throws IOException
*/
public static String webget(String urlStr, int timeout) throws IOException {
HttpURLConnection conn = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = "";
while ((temp=reader.readLine())!=null) {
sb.append(temp).append("\n");
}
/*int ch = is.read();
while (ch != -1) {
sb.append((char) ch);
ch = is.read();
}*/
} catch (IOException e) {
log.error("在访问链接"+urlStr+"时,出现异常!",e);
e = new IOException("1");
throw e;
} finally {
if (conn != null) {
conn.disconnect();
}
try {
if (null != is)
is.close();
} catch (IOException e) {
e = new IOException("2");
throw e;
}
}
return sb.toString().trim();
}
/**
* 发送带有表单参数的POST请求
*
* @param requestUrl 请求的地址(不含参数)
* @return 响应内容
*/
@SuppressWarnings({ "finally", "unused" })
public static String sendPostRequest(String requestUrl,String[] param,String[] values) {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
HttpClient httpClient = new DefaultHttpClient(); // 创建默认的httpClient实例
HttpPost httpPost = new HttpPost(requestUrl); // 创建HttpPost
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
for(int i =0;i<param.length;i++){
String p = param[i];
String v = values[i];
formParams.add(new BasicNameValuePair(p,v));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost); // 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity); // Consume response content
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown(); // 关闭连接,释放资源
return responseContent;
}
}
}