Java发送post请求

package com.baoxiu.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * 发送URL的post请求
 * User: HYY
 * Date: 13-8-16
 * Time: 下午4:44
 * To change this template use File | Settings | File Templates.
 */
public class SendPost {

    /**
     * 发送URL的post请求
     *
     * @param urlStr 请求的链接
     * @param params 请求的参数
     */
    public String sendUrl(String urlStr, String params) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            URL realUrl = new URL(urlStr);
            //打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            //这里设置火狐浏览器 V23
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(params);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    public static void main(String args[]) {
        String urlStr = "http://reg.email.163.com/unireg/call.do?cmd=added.mobilemail.checkBinding";
        String urlStr2 = "http://reg.email.163.com/unireg/call.do?cmd=register.formLog";
        String urlStr3 = "http://reg.email.163.com/unireg/call.do?cmd=added.mobileverify.sendAcode";
        String params = "mobile=13737461234";
        String params2 = "opt=write_field&flow=mobile&field=mobile&result=done&timecost=6847&level=info";
        String params3 = "mobile=13737461234&uid=13737461234%40163.com&mark=mobile_start";
        new SendPost().sendUrl(urlStr, params);
        new SendPost().sendUrl(urlStr2, params2);
        new SendPost().sendUrl(urlStr3, params3);
    }
}

posted @ 2013-08-16 18:53  无忧之路  阅读(2172)  评论(0编辑  收藏  举报
无忧之路