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

/**
* 发送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. preg_quote

    $p = 'http://'; $p = '/'.preg_quote($p, '/').'/'; echo $p; /http\:\/\//

  2. [LeetCode] 857. Minimum Cost to Hire K Workers 雇K个工人的最小花费

    There are N workers.  The i-th worker has a quality[i] and a minimum wage expectation wage[i]. Now w ...

  3. ASP.NET Core Restful Web API 相关资源索引

    GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...

  4. Kubernetes & Docker 容器网络终极之战(十四)

    目录 一.单主机 Docker 网络通信 1.1.host 模式 1.2 Bridge 模式 1.3 Container 模式 1.4.None 模式 二.跨主机 Docker 网络通信分类 2.1 ...

  5. LeetCode 496. 下一个更大元素 I(Next Greater Element I) 35

    496. 下一个更大元素 I 496. Next Greater Element I 题目描述 给定两个没有重复元素的数组 nums1 和 nums2,其中 nums1 是 nums2 的子集.找到  ...

  6. day27——面向对象的总结、异常处理

    day27 面向对象的总结 异常处理 错误的分类 语法错误 if if 2>1 print(222) dic = {"name"; "alex"} 逻辑错 ...

  7. 5. JDBC/ODBC服务器

    Spark SQL也提供JDBC连接支持,这对于让商业智能(BI)工具连接到Spark集群上以及在多用户间共享一个集群的场景都非常有用.JDBC服务器作为一个独立的Spark驱动器程序运行,可以在多用 ...

  8. SpringCloudConfig相关配置简介、使用、整合Eureka

    目的: 1.SpringCloud Config简介 2.Config Server基本使用 3.Config Client基本使用 4.Config整合Eureka 5.Config配置搜索路径 S ...

  9. jvm问题排查工具、命令

    dump生成:jmp -dump:live,format=b,file=/tmp/some.bin PID.其中,加上live表示只dump存活的对象. 线程栈信息生成:jstack PID > ...

  10. gitlab-runner 安装使用

    gitlab-runner 安装使用 gitlab-runner 是一个开源的与 gitlab CI 配合使用的项目,用于运行任务,并将结果返回 gitlab 本文通过docker in docker ...