之前的文章介绍过通过报文的方式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();
}

结束!

②HttpURLConnection通过Json参数方式提交Post请求的更多相关文章

  1. Android 使用HttpClient方式提交POST请求

    final String username = usernameEditText.getText().toString().trim(); final String password = passwr ...

  2. Android 使用HttpClient方式提交GET请求

    public void httpClientGet(View view) { final String username = usernameEditText.getText().toString() ...

  3. nodejs的http.request使用post方式提交数据请求

    官方api文档 http://nodejs.org/docs/v0.6.1/api/http.html#http.request虽然也有POST例子,但是并不完整. 直接上代码:http_post.j ...

  4. bootstrap分页查询传递中文参数到后台(get方式提交)

    <!--分页 --> <div style="width: 380px; margin: 0 auto; margin-top: 50px;"> <u ...

  5. C# ContentType: "application/json" 请求方式传json参数问题

    处理Http请求时遇到的ContentType为application/json方式,记录下这种Post请求方式下如何传json参数: var request = (HttpWebRequest)We ...

  6. 黎活明8天快速掌握android视频教程--27_网络通信之通过GET和POST方式提交参数给web应用

    1该项目主要实现Android客户端以get的方式或者post的方式向java web服务器提交参数 Android客户端通过get方式或者post方式将参数提交给后台服务器,后台服务器对收到的参数进 ...

  7. android 之HttpURLConnection的post,get方式请求数据

    get方式和post方式的区别: 1.请求的URL地址不同: post:"http://xx:8081//servlet/LoginServlet" get:http://xxx: ...

  8. 导出excel时,以form方式提交json数据

    今天在写项目时写到一个excel的导出,开始想用ajax请求后台后导出,但发现ajax会有返回值,而且ajax无法直接输出文件,而后台的excel导出方法已经封装好,不方便修改. 就改用了提交的方式f ...

  9. node.js 下依赖Express 实现post 4种方式提交参数

    上面这个图好有意思啊,哈哈, v8威武啊.... 在2014年的最后一天和大家分享关于node.js 如何提交4种格式的post数据. 上上一篇说到了关于http协议里定义的4种常见数据的post方法 ...

随机推荐

  1. Linux中df命令查询磁盘信息和fdisk命令分区的用法

    df - 报告文件系统磁盘空间的使用情况  总览 df [OPTION]... [FILE]... POSIX 选项: [-kP] GNU 选项 (最短方式): [-ahHiklmPv] [-t fs ...

  2. [BZOJ1018]堵塞的交通traffic

    Description 有一天,由于某种穿越现象作用,你来到了传说中的小人国.小人国的布局非常奇特,整个国家的交通系统可以被看成是一个2行C列的矩形网格,网格上的每个点代表一个城市,相邻的城市之间有一 ...

  3. Java Collections Framework Java集合框架概览

    Java SE documents -- The Collections Framework http://docs.oracle.com/javase/8/docs/technotes/guides ...

  4. Ajax -- 原理及简单示例

    1. 什么是Ajax •Ajax被认为是(AsynchronousJavaScript and XML的缩写).现在,允许浏览器与服务器通信而无须刷新当前页面的技术都被叫做Ajax. 2. Ajax ...

  5. srm开发(基于ssh)(4)

    1 input处理内容补充 -在struts2里面有错误处理机制,当上传文件超过默认的大小,自动返回结果input -在struts.xml中配置input的返回结果 <!-- 配置input结 ...

  6. spring3: 表达式5.2 SpEL基础

    5.1  概述 5.1.1  概述 Spring表达式语言全称为“Spring Expression Language”,缩写为“SpEL”,类似于Struts2x中使用的OGNL表达式语言,能在运行 ...

  7. axios 讲解 和vue搭建使用

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. LeetCode OJ:Majority Element II(主元素II)

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorit ...

  9. git修改远端服务器地址

    方法有三种: 1.修改命令 git remote set-url origin [url] 2.先删后加 git remote rm origingit remote add origin [url] ...

  10. sphinx使用

    一. 1.先得包含下载的文件 include'./sphinx/api/sphinxapi.php'; $sphinx= new SphinxClient(); $sphinx->SetServ ...