请求一个url 获得返回结果(doPost doGet方式)

来源:互联网 发布:mac能装千牛吗 编辑:程序博客网 时间:2024/06/06 02:06
public static String post(String urlStr, Map<String, String> map) {
        if (urlStr == null || map == null || map.size() == 0) {
            return null;
        }
        try {
            StringBuffer urt = new StringBuffer();
            urt.append(urlStr);
            urt.append("?");
            boolean add = true;
            for (Entry e : map.entrySet()) {
                if (add) {
                    add = false;
                } else {
                    urt.append("&");
                }
                urt.append(e.getKey());
                urt.append("=");
                urt.append(e.getValue() == null ? "" : e.getValue());
            }
            String responseContent = null;
            HttpURLConnection url_con = null;
            URL url = new URL(urt.toString());

            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("POST");

            url_con.setDoOutput(true);

            StringBuffer params = new StringBuffer();
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();
            url_con.setReadTimeout(1500);
            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            while (tempLine != null) {
                tempStr.append(tempLine);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
    //        System.out.println(tempStr.toString());
            return tempStr.toString();
        } catch (Exception e1) {
            return null;
        }
    }