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

/**
* 发送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. 使用draw.io桌面版代替visio制作流程图

    前言 draw.io是一款在github上的开源产品,由于需要构建在线文档,需要插入画图类型, 对比多款开源产品,最终选择了draw.io. draw.io图标资源非常的丰富,方便导入图标资源,基本上 ...

  2. consul ACL 配置范例

    service "dashboard" { policy = "write" } service "dashboard-sidecar-proxy&q ...

  3. LeetCode 201. 数字范围按位与(Bitwise AND of Numbers Range)

    201. 数字范围按位与 201. Bitwise AND of Numbers Range 题目描述 给定范围 [m, n],其中 0 <= m <= n <= 214748364 ...

  4. LeetCode 23. 合并K个排序链表(Merge Two Sorted Lists)

    23. 合并K个排序链表 23. Merge k Sorted Lists 题目描述 合并 k 个排序链表,返回合并后的排序链表.请分析和描述算法的复杂度. LeetCode23. Merge k S ...

  5. tetetet

    http://www.wuwenhui.cn/2623.html http://www.360doc.com/content/16/1104/09/36005694_603810507.shtml

  6. C++容器简介1—stack

    一.简介 stack是一种容器适配器(STL的容器分为顺序容器和关联容器,容器适配器),被设计来用于操作先进后出(FILO)结构的情景,在这种情况下, 元素的插入和删除都只能在容器的尾部进行. sta ...

  7. Json 文件读写以及和IniFile 转换

    JSON 文件是越来越受欢迎了,以前程序配置文件用Ini,Ini 简练,简单.方便,但是也有不少缺点,比如,没有 JSON 直观,无法存储复杂点的数据类型. 于是乎,我封装了一个TJsonFile 的 ...

  8. ubuntu 使用新添加的用户登录只有$解决方法

    在ubuntu中,使用useradd新建的用户,默认使用的shell是dash,导致界面不美观,操作也不舒服. 情况如下: 只有美元符,不显示用户,很多乱码,且文件没有颜色. 解决方法,将该用户使用的 ...

  9. L2R 一:基础知识介绍

    一.背景 l2r可以说是搜索推荐里面很常用的知识了,一直处于一知半解的地步,今天开个博客准备把这些零散的东西系统性整理好,一版就粗糙点了. 二.粗概 前段时间的项目主要和搜索引擎相关,记录下搜索引擎的 ...

  10. (二)pdf的构成综述

    引自:https://blog.csdn.net/steve_cui/article/details/81948486 一个pdf文件主要是由4部分构成:文件头.文件体.交叉引用表.文件尾 文件头:用 ...