当前位置 : 主页 > 手机开发 > 其它 >

简单封装 HTTP 请求工具类

来源:互联网 收集:自由互联 发布时间:2021-06-19
/** * 简单封装 HTTP 请求工具类 */ public static String doPost(String requestUrl, MapString, String params) throws Exception { // 获取连接 URL url = new URL(requestUrl); HttpURLConnection urlConn = (HttpURLConnection) url.openCo
/**
     * 简单封装 HTTP 请求工具类
     */
    public static String doPost(String requestUrl, Map<String, String> params) throws Exception {
// 获取连接
        URL url = new URL(requestUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setConnectTimeout(15 * 1000);
        urlConn.setReadTimeout(15 * 1000);
        urlConn.setDoOutput(true);
// 格式化请求参数
        StringBuffer sb = new StringBuffer();
        for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            sb.append(name + "=").append(params.get(name));
            if (iter.hasNext()) {
                sb.append("&");
            }
        }
// 向服务端写出请求参数
        byte[] b = sb.toString().getBytes(CHARSEST);
        urlConn.getOutputStream().write(b, 0, b.length);
        urlConn.getOutputStream().flush();
        urlConn.getOutputStream().close();
// 获取响应
        InputStream in = null;
        BufferedReader rd = null;
        try {
            if (urlConn.getResponseCode() == 200) {
                in = urlConn.getInputStream();
            } else {
                in = urlConn.getErrorStream();
            }
            rd = new BufferedReader(new InputStreamReader(in, CHARSEST));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            return tempStr.toString();
        } finally {
            if (rd != null) {
                rd.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }
网友评论