通过响应状态来判断是否读取数据与抛出异常,然后通过判断获取的字节数去读取数据或抛出异常

/**
* 发送HttpPost请求
* @param strURL
* 服务地址
* @param params
* 请求数据
* @param logIO
* 是否打印输入输出
* @return 成功:返回json字符串<br/>
*
*/

public static String postJson(String strURL, Object params, boolean logIO) {

log.info("requestUrl = " + strURL);
try {
URL url = new URL(strURL);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // 设置发送数据的格式
connection.setRequestProperty("authorization","xxxxxxxxxxxxxxxx");
/*
* if (logIO) {
* connection.setRequestProperty("X-Xencio-Client-Id",PropUtil.getString(
* "ecustom", "jz.token.Access")); }
*///1ae1ea37f00207df4a76e1cde621db93
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "UTF-8"); // utf-8编码
String inputJson = new Gson().toJson(params);
if (logIO) {
log.info("inputJson = " + inputJson);
} else {
log.debug("inputJson = " + inputJson);
}
out.append(inputJson);
out.flush();
out.close();

int code = connection.getResponseCode();
InputStream is = null;
if (code == 200) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}

// 读取响应
int length = (int) connection.getContentLength();// 获取长度
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String result = new String(data, "UTF-8"); // utf-8编码
if (logIO) {
log.info("outputJson = " + result);
} else {
log.debug("outputJson = " + result);
}
return result;
}

} catch (IOException e) {
log.error("Exception occur when send http post request!", e);
}
return "error"; // 自定义错误信息
}

测试类

import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import ecustom.commons.HttpRequestUtil;
import ecustom.ecology8.commons.PropUtil;

@Test

public void testPostInteface(){

String resutl=HttpRequestUtil.postJson(url, json,true);

JSONObject jsonObject= JSON.parseObject(resutl);
String data = jsonObject.getString("data");
JSONObject jsondata= JSON.parseObject(data);
String token = jsondata.getString("tokenid");

System.out.println("指定值:"+token );

}

POST请求通过输入输出流来显示读取数据

/**
* 向指定的 URL发送远程POST方法的请求
* @param url发送请求的 URL
* @param 入参
* @return 所代表远程资源的响应结果
*/
public static JSONObject sendPost(String url, Object params) {
//PrintWriter out = null;

DataOutputStream out=null;
BufferedReader in = null;
JSONObject jsonObject = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
// 设置通用的请求属性
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST"); // 设置请求方式
//设置发送数据的格式
conn.setRequestProperty("Accept", "application/json");
//设置请求属性
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
// 发送POST请求必须设置下面的属性
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);

conn.connect();
// 获取URLConnection对象对应的输出流
//out = new PrintWriter(conn.getOutputStream());

out=new DataOutputStream(conn.getOutputStream());

// 发送请求参数
String paramsVal = new Gson().toJson(params);
//out.print(paramsVal);服务器部署出现(操作系统与服务器系统)字符不统一现象
out.writechars(paremsVal);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
result += line;
}
//将返回结果转换为字符串
jsonObject = JSONObject.parseObject(result);
}catch (IOException e) {
log.error("Exception occur when send http post request!", e);
}catch (Exception e) {
throw new RuntimeException("远程通路异常"+e.toString());

}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return jsonObject;
}

POST请求接口实列的更多相关文章

  1. Hbase之必要时取出请求的行(列族所有数据)

    import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.CellScanner; import org. ...

  2. vue---发送数据请求的一些列的问题

    使用vue做数据请求,首先考虑的是封装请求方法request.js import axios from 'axios' import Qs from 'qs' // 创建一个axios实例 const ...

  3. DataTable 除去列中重复值

    DataTable dtPCI = dtblSourceData.DefaultView.ToTable(true, new string[] { "Server Cell PCI" ...

  4. SQL语句的Select部分只写必要的列

    如果Select部分包含不需要的列,这会强制DB2必须进入数据页来得到所请求的特定列,这就要求更多的I/O操作.另外,如果再对这个不需要的列进行排序,就需要创建和传递一个更大的排序文件,相应地会使排序 ...

  5. MVC应用程序请求密码的功能(二)

    MVC应用程序请求密码的功能(二) 在完成<MVC应用程序请求密码的功能(一)>http://www.cnblogs.com/insus/p/3471534.html之后,如果你照着做,所 ...

  6. SQL Server覆盖索引--有无包含列对数据库查询性能的影响分析

    “覆盖索引使您能够避免返回到表中以满足请求的所有列,因为所有请求的列都已经存在于非聚集索引中.这意味着您还可以避免返回到表中进行任何逻辑或物理的信息读取.” 然而,以上这不是我想要传达的全部意思,因为 ...

  7. Fiddler抓取HTTP请求

    参考链接:http://blog.csdn.net/ohmygirl/article/details/17849983/ http://www.cnblogs.com/kingwolf_JavaScr ...

  8. Fiddler抓取HTTP请求。

    参考链接:http://blog.csdn.net/ohmygirl/article/details/17849983/ http://www.cnblogs.com/kingwolf_JavaScr ...

  9. 《MSSQL2008技术内幕:T-SQL语言基础》读书笔记(上)

    索引: 一.SQL Server的体系结构 二.查询 三.表表达式 四.集合运算 五.透视.逆透视及分组 六.数据修改 七.事务和并发 八.可编程对象 一.SQL Server体系结构 1.1 数据库 ...

随机推荐

  1. 通过Onvif设备探索获取EasyNVR网页无插件播放所需要的摄像机硬盘录像机NVR的RTSP地址

    想实现网络监控摄像头进行视频直播的朋友门应该知道,方法其实非常简单,你不需要使用支持直播的网络摄像机,只需要经过一套流媒体服务器将监控摄像头的RTSP视频流转为RTMP\HLS\HTTP-FLV视频流 ...

  2. Python的dict字典结构操作方法学习笔记

    Python的dict字典结构操作方法学习笔记 这篇文章主要介绍了Python的dict字典结构操作方法学习笔记本,字典的操作是Python入门学习中的基础知识,需要的朋友可以参考下 一.字典的基本方 ...

  3. Spring MVC -- 转换器和格式化

    在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...

  4. [LeetCode] 361. Bomb Enemy 炸敌人

    Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return ...

  5. linux:使用python脚本监控某个进程是否存在(不使用crontab)

    背景: 需要每天定时去检测crontab进程是否启动,所以不能用crontab来启动检测脚本了,直接使用while 循环和sleep方式实现定时检测 # coding:utf-8 import os ...

  6. 日志收集系统ELK搭建

    一.ELK简介 在传统项目中,如果在生产环境中,有多台不同的服务器集群,如果生产环境需要通过日志定位项目的Bug的话,需要在每台节点上使用传统的命令方式查询,这样效率非常低下.因此我们需要集中化的管理 ...

  7. Spring的日志管理

    一.spring的日志依赖 Logging是spring中唯一强制的外部依赖,spring中默认使用的日志是commons-logging,简称JCL,这里说的强制性,是因为在spring-core这 ...

  8. 【转帖】处理器的三国时代:DR公司盛气凌人,IBM转身成就微软

    处理器的三国时代:DR公司盛气凌人,IBM转身成就微软 https://www.eefocus.com/mcu-dsp/360555 <处理器史话>之五 2016-04-06 15:24  ...

  9. sql查询出现1055 this is incompatible with sql_mode=only_full_group_by

    今天在测试服务器上突然出现了这么一个MySQL的问题,同样的代码正式服没有问题,那肯定就是出在了配置上,查了一下原因才明白原来是数据库版本为5.7以上的版本, 默认是开启了 only_full_gro ...

  10. 《Redis Mysql 双写一致性问题》

    一:序 - 最近在对数据做缓存时候,会涉及到如何保证 数据库/Redis 一致性问题. - 刚好今天来总结下 一致性问题 产生的问题,和可能存在的解决方案. 二:(更新策略)-  先更新数据库,后更新 ...