之前的文章介绍过通过报文的方式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. 多线程、多进程、协程、IO多路复用请求百度

    最近学习了多线程.多进程.协程以及IO多路复用,那么对于爬取数据来说,这几个方式哪个最快呢,今天就来稍微测试一下 普通方式请求百度5次 import socket import time import ...

  2. maven中使用dom4j解析、生成XML的简易方法

    此片文章主要写一些关于如何在maven工程中使用dom4j来解析或生成XML的建议方法,实际可使用的写法不仅限于如下所写的样例代码.此处进攻快速入手和提供思路使用. 首先配置pom.xml中的依赖的包 ...

  3. Contest-hunter 暑假送温暖 SRM01

    一直找不到好的题去做...于是想到了srm...回来补题...QAQ 从srm01补起 A 题意:n个数,排成一列,刚开始都是1,如果左右相等就可以合并,问最后的数列长什么样. 思路:比赛的时候直接敲 ...

  4. java 判断对象的所有属性是否为空解决方案

    public static boolean allfieldIsNUll(Object o){ try{ for(Field field:o.getClass().getDeclaredFields( ...

  5. 给定字符串数组,用map的key保存数组中字符串元素,value保存字符串元素出现次数,最后统计个字符串元素出现次数

    import java.util.HashMap; public class map1 { public static void main(String[] args) { String[] arra ...

  6. bzoj 2190: [SDOI2008]仪仗队 线性欧拉函数

    2190: [SDOI2008]仪仗队 Time Limit: 10 Sec  Memory Limit: 259 MB[Submit][Status][Discuss] Description 作为 ...

  7. 一些官方的github地址

    阿里巴巴开源github地址:https://github.com/alibaba 腾讯开源github地址:https://github.com/Tencent 奇虎360github地址:http ...

  8. canvas画的北斗七星和大熊座

    用canvas画的北斗七星和大熊座,主要用到的知识点是:canvas.定时器. html代码: <body> <canvas id="canvas" width= ...

  9. 关于Action和EventHandler

    .net框架自带的两个常用类(Action和EventHandler),当然这两个类型的也可以自定义,但系统已经提供,直接拿来用即可,很方便 1:Action : 引用“void方法”的委托,目前框架 ...

  10. iOS自动化探索(二)WDA API的使用

    前面我们已经安装好了WebdriverAgent, 现在可以用Facebook官方提供的API来进行一些操作 WDA API官方页面: https://github.com/facebook/WebD ...