码迷,mamicode.com
首页 > 编程语言 > 详细

java 使用原生HttpURLConnection发送post请求

时间:2019-03-05 14:05:53      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:form   set   log4   false   war   result   line   trace   adl   

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;

public class RequestDoPostUtil {
    private static Logger log = Logger.getLogger(RequestDoPostUtil.class);
    
    public static String doPost(String url, Map<String, Object> parameters) throws Exception {
        // 编码请求参数
        String params = paramsConvert(parameters);
        URL restURL = new URL(url);
        
        log.info("链接:"+url);
        log.info("参数:"+parameters.toString());
        
        int t= 0;//调用接口出错次数
        while(t<3) {
            try {
                /*
                 * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类
                 * 的子类HttpURLConnection
                 */
                HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
//                conn.setConnectTimeout(5000);
//                conn.setReadTimeout(5000);
                // 请求方式
                conn.setRequestMethod("POST");
                // 设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true);
                conn.setDoOutput(true);
                // allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
                conn.setAllowUserInteraction(false);

                PrintStream ps = new PrintStream(conn.getOutputStream());
                ps.print(params);

                ps.close();

                BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                String line, resultStr = "";

                while (null != (line = bReader.readLine())) {
                    resultStr += line;
                }
                System.out.println(resultStr);
                bReader.close();

                return resultStr;
            } catch (Exception e) {
                t++;
                log.warn("=======>出错次数(requset error ):" + t);
                e.printStackTrace();
            }
        }
        
        throw new Exception("网络异常,请稍后再试");

    }
    
    /**
     * 参数类型转换
     * 
     * @param parameters
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String paramsConvert(Map<String, Object> parameters) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();// 处理请求参数
        // 编码请求参数
        for (String name : parameters.keySet()) {
            Object object = parameters.get(name);
            log.info("类型:"+object.getClass());
            if(object instanceof Integer) {
                sb.append(name).append("=").append(java.net.URLEncoder.encode((String)object, "UTF-8"))
                .append("&");
            }else if(object instanceof Date) {
                Calendar cal = Calendar.getInstance();
                cal.setTime((Date)object);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sb.append(name).append("=").append(java.net.URLEncoder.encode(sdf.format(cal.getTime()), "UTF-8"))
                .append("&");
            }else{
                if(object.getClass().isArray()) {//判断是否是字符串数组
                    String[] values = (String[])object;
                    for(String va : values) {
                        sb.append(name).append("=").append(java.net.URLEncoder.encode((String) va, "UTF-8"))
                        .append("&");
                    }
                }else {
                    sb.append(name).append("=").append(java.net.URLEncoder.encode((String) parameters.get(name), "UTF-8"))
                    .append("&");
                }
            }
        }
        return sb.toString().substring(0, sb.toString().length()-1);
    }
    
    public static void main(String[] args) {
        int s = 0;
        Object o = (Object)s;
        log.info(o.getClass());
        Integer a = 0;
        log.info(a.getClass());
        Date b = new Date();
        log.info(b.getClass());
        String c = "";
        log.info(c.getClass());
        String [] d = new String[2];
        log.info(d.getClass());
    }
}

 

java 使用原生HttpURLConnection发送post请求

标签:form   set   log4   false   war   result   line   trace   adl   

原文地址:https://www.cnblogs.com/lxk233/p/10476216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!