②HttpURLConnection通过Json参数方式提交Post请求

之前的文章介绍过通过报文的方式HttpURLConnection提交post请求,今天介绍下通过Json参数的方法提交Post请求,先上代码

 public static HttpResponse sendPost(String url, String param, Charset charset) {
        try {
            URL httpurl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) httpurl.openConnection();
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; "
                            + "Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            httpConn.setConnectTimeout(CONN_TIMEOUT);
            httpConn.setReadTimeout(READ_TIMEOUT);
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset.name());
            httpConn.connect();
            OutputStream os = httpConn.getOutputStream();
            PrintWriter out = new PrintWriter(os);
            out.print(param);
            out.flush();
            out.close();
            os.close();
            HttpResponse response = new HttpResponse();
            response.setResponseStatus(httpConn.getResponseCode());
            response.setContentLength(httpConn.getContentLength());
            response.setContentType(httpConn.getContentType());
            response.setHeaderFields(httpConn.getHeaderFields());
            if (response.getResponseStatus() != 200 && httpConn.getErrorStream() != null) {
                response.setErrorMessage(new String(IOUtils.readToByte(httpConn.getErrorStream()), charset));
                return response;
            }
            response.setResponseContent(httpConn.getInputStream());
            if (response.getContentType() == null || response.getContentType().startsWith("text")) {
                response.setContext(new String(IOUtils.readToByte(response.getResponseContent()), charset));
            }
            return response;
        }
        catch (IOException e) {
            throw new RuntimeException(String.format("url:%s,param:%s,message:%s", url, param, e.getMessage()), e);
        }
    }

我们先测试下:

 public static void main(String[] args) {
        HttpResponse resp = sendPost("http://www.cnblogs.com/shawWey/", "", Charset.forName("utf-8"));
        System.err.println(resp.getContext());
        System.err.println(resp.getErrorMessage());
    }

可以看到控制台输出


"zh-cn">

"utf-8"/>
"viewport" content="width=device-width, initial-scale=1" />
"referrer" content="origin" />
shawWey - 博客园
"text/css" rel="stylesheet" href="/bundles/blog-common.css?v=giTNza-Of-PEt5UsELhFQAR7G6-bfaSa4oolcq7i9-o1"/>
"MainCss" type="text/css" rel="stylesheet" href="/skins/darkgreentrip/bundle-darkgreentrip.css?v=EjExWsdi8Ql8RA7Wdq4_YaeuMVhIAL6d2BSGbilapWY1"/>
"mobile-style" media="only screen and (max-width: 767px)" type="text/css" rel="stylesheet" href="/skins/darkgreentrip/bundle-darkgreentrip-mobile.css?v=6NcJHqsIyaE4w19VtgFvCFahrnr2rYCTRRTdxlMDhhQ1"/>
"RSS" type="application/rss+xml" rel="alternate" href="https://www.cnblogs.com/shawWey/rss"/>
"RSD" type="application/rsd+xml" rel="EditURI" href="https://www.cnblogs.com/shawWey/rsd.xml"/>
"application/wlwmanifest+xml" rel="wlwmanifest" href="https://www.cnblogs.com/shawWey/wlwmanifest.xml"/>





"top">


可见这种请求是可以的,接下来看下,如何拼接Json参数

       Map params = new HashMap();
            params.put("apName", apName);
            params.put("apPassword", apPassword);
            params.put("srcId", srcId);
            params.put("ServiceId", ServiceId);
            params.put("sendTime", sendTime);
            params.put("content", "我是短信内容");
            params.put("calledNumber", "188888888888");

我们可以定义一个工具类进行参数的拼接

public class StringUtils {
    
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }
    
    public static String builderUrlParams(Map params){
        Set keySet = params.keySet();
        List keyList = new ArrayList(keySet);
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        for (String key : keyList) {
            String value = params.get(key);
            if (StringUtils.isEmpty(value)) {
                continue;
            }
            sb.append(key);
            sb.append("=");
            try {
                sb.append(URLEncoder.encode(params.get(key),"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

}

完整的实例代码如下:

            String postUrl ="postUrl我短信url";
            String apName = "apName";
            String apPassword = "apPassword";
            String srcId = "";
            String ServiceId = "";
            String sendTime = "";

            Map params = new HashMap();
            params.put("apName", apName);
            params.put("apPassword", apPassword);
            params.put("srcId", srcId);
            params.put("ServiceId", ServiceId);
            params.put("sendTime", sendTime);
            params.put("content", "我是短信内容");
            params.put("calledNumber", "188888888888");
            try {
                String param = StringUtils.builderUrlParams(params);
                HttpResponse response = HttpUtils.sendPost(postUrl, param, Charset.forName("utf-8"));
                String conent= response.getContext();
                int statusCode = response.getResponseStatus();
                if (statusCode == 200) {
                   //业务判断
                } else {
                    throw new IllegalStateException("返回HTTP状态码错误!httpStatus=" + statusCode + "; context=" + conent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

结束!

转载于:https://www.cnblogs.com/shawWey/p/9776358.html

你可能感兴趣的:(②HttpURLConnection通过Json参数方式提交Post请求)