http请求的方法

1. 第一种

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.weixin.bean.ResultJB;


/**
 * http请求
 *
 */

public class SafeHttp {

    private final static Logger logger = Logger.getLogger(SafeHttp.class);
    private final static String apiurl = ConfigUtils.getValue("api.url");

    /*-------------------------------HttpURLConnection-------------------------------*/
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param str
     *            请求数据
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String str) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        System.out.println("sendPost url=" + url);
        System.out.println("sendPost str=" + str);
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "text/html");
            conn.setRequestProperty("text/html", "utf-8");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 发送请求参数
            out.print(str);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println("sendPost result=" + result);
        return result;
    }
    
    /**
     * Http-Post请求
     *
     * @param
     * @param
     * @param jsons 请求接口时需要的参数的json串
     * @return 服务器返回数据的字节流
     * @throws Exception
     */
    public static ResultJB sendPost1(String url,String jsons) throws UnsupportedEncodingException, Exception {
        String code = "";
        String msg = "";
        String rel = "";
        ResultJB result = new ResultJB();
        String contentTemp = sendPost(url,jsons);
        System.out.println("result:::::::" + contentTemp);
        if (Utils.isEmpty(contentTemp)) {
            return null;
        }
        JSONObject json = JSONObject.fromObject(contentTemp);
        if (json.has("errorCode")) {
            code = json.getString("errorCode");
        }
        if (json.has("errorMessage")) {
            msg = json.getString("errorMessage");
        }
        if (json.has("data")) {
            rel = json.getString("data");
        }
        result.setErrorCode(code);
        result.setErrorMessage(msg);
        result.setData(rel);

        return result;
    }
    

    /**
     * Http-Post请求
     *
     * @param
     * @param
     * @param jsons 请求接口时需要的参数的json串
     * @return 服务器返回数据的字节流
     * @throws Exception
     */
    public static ResultJB post(String jsons) throws UnsupportedEncodingException, Exception {
        String code = "";
        String msg = "";
        String rel = "";
        ResultJB result = new ResultJB();
        String contentTemp = doPost(jsons, "UTF-8");
        System.out.println("result:::::::" + contentTemp);
        if (Utils.isEmpty(contentTemp)) {
            return null;
        }
        JSONObject json = JSONObject.fromObject(contentTemp);
        if (json.has("errorCode")) {
            code = json.getString("errorCode");
        }
        if (json.has("errorMessage")) {
            msg = json.getString("errorMessage");
        }
        if (json.has("data")) {
            rel = json.getString("data");
        }
        result.setErrorCode(code);
        result.setErrorMessage(msg);
        result.setData(rel);

        return result;
    }

    /*-------------------------------HttpClient-------------------------------*/

    /**
     * Http-Post请求
     *
     * @param
     * @param req 请求参数的字节数组
     * @return 服务器返回数据的json
     * @throws Exception
     */
    public static String doPost(String req, String encoding) throws UnsupportedEncodingException, IOException {
        System.out.println("url::" + apiurl + "?msg=" + req);
        String req_new = URLEncoder.encode(req);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(apiurl);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        Md5 md5 = new Md5();
        params.add(new BasicNameValuePair("msg", req));
        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(post);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            String content = EntityUtils.toString(response.getEntity(), encoding);
            return content;
        } else {
            return null;
        }
    }

    /**
     * Http-Post请求
     *
     * @param
     * @param map 请求参数
     * @return 服务器返回数据的json串
     * @throws Exception
     */
    public static String post(String path, Map<String, String> map) throws UnsupportedEncodingException, Exception {
        String code = "";
        String msg = "";
        String time = "";
        String rel = "";
        String result = doPost(path, map, "UTF-8");
        System.out.println("result:::::::" + result);

        return result;
    }

    /**
     * Http-Post请求
     *
     * @param
     * @param
     * @return 服务器返回数据的json
     * @throws Exception
     */
    public static String doPost(String path, Map<String, String> params, String encoding) throws UnsupportedEncodingException, IOException {
        List<NameValuePair> param = paramNameValuePair(params);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(param, encoding);
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost post = new HttpPost(path);
        post.setEntity(entity);
        HttpResponse response = httpclient.execute(post);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            String content = EntityUtils.toString(response.getEntity(), encoding);
            return content;
        } else {
            return null;
        }
    }


    /**
     * change Map into NameValuePair.
     *
     * @param
     */
    public static List<NameValuePair> paramNameValuePair(Map<String, String> params) {
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                param.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        return param;
    }

    /**
     * 执行一个HTTP GET请求,返回请求响应的HTML
     *
     * @param url         请求的URL地址
     * @param queryString 请求的查询参数,可以为null
     * @param charset     字符集
     * @param pretty      是否美化
     * @return 返回请求响应的HTML
     */
    public static String doGet(String url, String queryString, String charset, boolean pretty) {
        StringBuffer response = new StringBuffer();
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        try {
            if (StringUtils.isNotBlank(queryString))
                //对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串
                method.setQueryString(URIUtil.encodeQuery(queryString));
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
                String line;
                while ((line = reader.readLine()) != null) {
                    if (pretty)
                        response.append(line).append(System.getProperty("line.separator"));
                    else
                        response.append(line);
                }
                reader.close();
            }
        } catch (URIException e) {
            logger.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
        } catch (IOException e) {
            logger.error("执行HTTP Get请求" + url + "时,发生异常!", e);
        } finally {
            method.releaseConnection();
        }
        return response.toString();
    }
}

   

2.第二种

/**
     * POST请求
     *
     * @param msg
     * @return
     */
    public HttpMessage post(HttpMessage msg) {
        DefaultHttpClient htpc = HttpConnectionManager.getHttpClient();
        String s = null;
        HttpMessage httpMsg = null;
        HttpPost httpPost = null;
        try {
            httpPost = new HttpPost(msg.getUrl());
            if (msg.getParams() != null && msg.getParams().size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (Entry<String, Object> en : msg.getParams().entrySet()) {
                    sb.append("&")
                            .append(en.getKey())
                            .append("=")
                            .append(URLEncoder.encode(
                                    String.valueOf(en.getValue()), "utf-8"));
                }

                StringEntity entity = new StringEntity(sb.substring(1)
                        .toString(), ContentType.create("text/html", "utf-8"));
                httpPost.setEntity(entity);
            }
//            httpPost.setHeader("Accept-Encoding", "gzip, deflate");
            HttpResponse resp = htpc.execute(httpPost);

            int status = resp.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                // gzip 接口
                s = this.getResponseBody(resp);
            }
            httpMsg = new HttpMessage(status, s);

        } catch (Exception e) {
            httpMsg = new HttpMessage(500, e.getMessage());
            httpPost.abort();
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }

        return httpMsg;
    }

    /**
     * GET请求
     *
     * @param msg
     * @return
     */
    public HttpMessage get(HttpMessage msg) {
        DefaultHttpClient htpc = HttpConnectionManager.getHttpClient();
        String s = null;
        HttpMessage httpMsg = null;
        HttpGet httpGet = null;
        try {
            StringBuilder sb = new StringBuilder();
            String url = msg.getUrl();
            if (msg.getParams() != null && msg.getParams().size() > 0) {
                for (Entry<String, Object> en : msg.getParams().entrySet()) {
                    sb.append("&")
                            .append(en.getKey())
                            .append("=")
                            .append(URLEncoder.encode(
                                    String.valueOf(en.getValue()), "utf-8"));
                }
                url = msg.getUrl()
                        + (msg.getUrl().contains("?") ? sb.toString() : "?"
                                + sb.substring(1).toString());
            }
            if(logger.isDebugEnabled()){
                logger.debug("请求论坛URL:"+url);
            }
            httpGet = new HttpGet(url);
//            httpGet.setHeader("Accept-Encoding", "gzip, deflate");
            HttpResponse resp = htpc.execute(httpGet);
            int status = resp.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                // gzip 接口
                s = this.getResponseBody(resp);
            }
            httpMsg = new HttpMessage(status, s);
        } catch (Exception e) {
            httpMsg = new HttpMessage(500, e.getMessage());
            httpGet.abort();
        } finally {
            httpGet.releaseConnection();
        }

        return httpMsg;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值