好用的http工具

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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值