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

/**
* 发送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. PAT 甲级 1079 Total Sales of Supply Chain (25 分)(简单,不建树,bfs即可)

    1079 Total Sales of Supply Chain (25 分)   A supply chain is a network of retailers(零售商), distributor ...

  2. 元数据Meta

    元数据,指的是“除了字段外的所有内容”,例如排序方式.数据库表名.人类可读的单数或者复数名等等.所有的这些都是非必须的,甚至元数据本身对模型也是非必须的. 在模型中增加元数据,需要在模型类中添加一个子 ...

  3. Centos7安装图形界面桌面

    查看是否存在图形安装包.如果包含GNOME Desktop,则说明已存在. yum grouplist 安装图形化包 yum groupinstall "GNOME Desktop" ...

  4. 【SSH进阶之路】Spring的IOC逐层深入——为什么要使用IOC[实例讲解](二)

    上篇博客[SSH进阶之路]Spring简介,搭建Spring环境——轻量级容器框架(一),我们简单的介绍了Spring的基本概念,并且搭建了两个版本的Spring开发环境,但是我们剩下了Spring最 ...

  5. java开发异常Exception集锦

    背景:整理开发过程中的异常问题 java.lang.Exception: No tests found matching 一般出现在新导入的工程中.在sts中通过open project的方式导入工程 ...

  6. 【转】Axure RP9.0.0.3661Team Edition激活码

    被授权人:Axure 授权密码:ydiJnG8quHEhHLu/MWonjkeul5LYB1+tX9fyPVnpdmU0cb/NJzVs45uD7z5Iswmi 转载于:http://menvscod ...

  7. Jenkins插件、war下载地址

    1.jenkins的war包下载地址 地址:http://mirrors.jenkins-ci.org/,打开链接后,表格有war列,Releases行是短期更新包.LTS是长期更新包.一般选择Rel ...

  8. python实践项目七:正则表达式版本的strip()函数

    描述:写一个函数,它接受一个字符串,做的事情和 strip()字符串方法一样.如果只传入了要去除的字符串, 没有其他参数, 那么就从该字符串首尾去除空白字符:否则, 函数第二个参数指定的字符将从该字符 ...

  9. 嵌入式02 STM32 实验01 端口复用和重映射

    内设与外设: 端口复用和端口重映射都需要了解内设和外设,那么什么是内设?什么是外设? 内设:单片机内部集成的功能一般包括:串口模块.SPI模块(Serial Peripheral Interface  ...

  10. tensorflow-简单的神经网络

    本次笔记是关于tensorflow1的代码,由于接触不久没有跟上2.0版本,这个代码是通过简单的神经网络做一个非线性回归任务,(如果用GPU版本的话第一次出错就重启) import tensorflo ...