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

时间:2023-03-09 05:19:35
②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() != && 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());
}

可以看到控制台输出

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="referrer" content="origin" />
<title>shawWey - 博客园</title>
<link type="text/css" rel="stylesheet" href="/bundles/blog-common.css?v=giTNza-Of-PEt5UsELhFQAR7G6-bfaSa4oolcq7i9-o1"/>
<link id="MainCss" type="text/css" rel="stylesheet" href="/skins/darkgreentrip/bundle-darkgreentrip.css?v=EjExWsdi8Ql8RA7Wdq4_YaeuMVhIAL6d2BSGbilapWY1"/>
<link id="mobile-style" media="only screen and (max-width: 767px)" type="text/css" rel="stylesheet" href="/skins/darkgreentrip/bundle-darkgreentrip-mobile.css?v=6NcJHqsIyaE4w19VtgFvCFahrnr2rYCTRRTdxlMDhhQ1"/>
<link title="RSS" type="application/rss+xml" rel="alternate" href="https://www.cnblogs.com/shawWey/rss"/>
<link title="RSD" type="application/rsd+xml" rel="EditURI" href="https://www.cnblogs.com/shawWey/rsd.xml"/>
<link type="application/wlwmanifest+xml" rel="wlwmanifest" href="https://www.cnblogs.com/shawWey/wlwmanifest.xml"/>
<script src="//common.cnblogs.com/scripts/jquery-2.2.0.min.js"></script>
<script type="text/javascript">var currentBlogApp = 'shawWey', cb_enable_mathjax=false;var isLogined=false;</script>
<script src="/bundles/blog-common.js?v=fobKU6DuMF7uNOMKEOEwhhLiN2dvU4IL2UfTDgUZOsY1" type="text/javascript"></script>
</head>
<body>
<a name="top"></a> <!--done-->
<div id="home">
<div id="header">
<div id="blogTitle">
<a id="lnkBlogLogo" href="https://www.cnblogs.com/shawWey/"><img id="blogLogo" src="/Skins/custom/images/logo.gif" alt="返回主页" /></a> <!--done-->
<h1><a id="Header1_HeaderTitle" class="headermaintitle" href="https://www.cnblogs.com/shawWey/">shawWey</a></h1>
<h2>知识的搬运工~~~浪里格朗</h2> </div><!--end: blogTitle 博客的标题和副标题 -->
<div id="navigator"> <ul id="navList">
<li><a id="blog_nav_sitehome" class="menu" href="https://www.cnblogs.com/">博客园</a></li>
<li><a id="blog_nav_myhome" class="menu" href="https://www.cnblogs.com/shawWey/">首页</a></li>
<li><a id="blog_nav_newpost" class="menu" rel="nofollow" href="https://i.cnblogs.com/EditPosts.aspx?opt=1">新随笔</a></li>
<li><a id="blog_nav_contact" class="menu" rel="nofollow" href="https://msg.cnblogs.com/send/shawWey">联系</a></li>
<li><a id="blog_nav_rss" class="menu" href="https://www.cnblogs.com/shawWey/rss">订阅</a>
<!--<a id="blog_nav_rss_image" class="aHeaderXML" href="https://www.cnblogs.com/shawWey/rss"><img src="//www.cnblogs.com/images/xml.gif" alt="订阅" /></a>--></li>
<li><a id="blog_nav_admin" class="menu" rel="nofollow" href="https://i.cnblogs.com/">管理</a></li>
</ul>
<div class="blogStats"> <div id="blog_stats">
<span id="stats_post_count">随笔 - &nbsp; </span>
<span id="stats_article_count">文章 - &nbsp; </span>
<span id="stats-comment_count">评论 - </span>
</div> </div><!--end: blogStats -->
</div><!--end: navigator 博客导航栏 -->
</div><!--end: header 头部 --> <div id="main">
<div id="mainContent">
<div class="forFlow"> <!--done--> .................

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

       Map<String, String> params = new HashMap<String, String>();
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", "");

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

public class StringUtils {

    public static boolean isEmpty(String str) {
return str == null || str.length() == ;
} public static String builderUrlParams(Map<String, String> params){
Set<String> keySet = params.keySet();
List<String> keyList = new ArrayList<String>(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() - );
return sb.toString();
} }

完整的实例代码如下:

            String postUrl ="postUrl我短信url";
String apName = "apName";
String apPassword = "apPassword";
String srcId = "";
String ServiceId = "";
String sendTime = ""; Map<String, String> params = new HashMap<String, String>();
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", "");
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 == ) {
//业务判断
} else {
throw new IllegalStateException("返回HTTP状态码错误!httpStatus=" + statusCode + "; context=" + conent);
}
} catch (Exception e) {
e.printStackTrace();
}

结束!