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

/**
* 发送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. Qt编写安防视频监控系统14-本地回放

    一.前言 在上一篇文章将视频文件存储好了,需要提供界面方便用户查询视频文件进行回放,其实这个回放就是播放历史存储的视频文件,并不是什么高大上的东西,视频回放在这个系统中分三种,第一种是本地回放,回放存 ...

  2. [Math] From Prior to Posterior distribution

    贝叶斯统计推断 后验分布与充分性 无信息先验下的后验分布 共轭先验(conjugacy)下的后验分布 其中,正态分布的共轭先验推导过程,典型且重要. (1) 当方差已知时,均值(prior: 高斯分布 ...

  3. mysql or条件查询优化

    当使用or的时候是不会用到索引的 explain SELECT * FROM aladdin_resource WHERE state = 1 OR state = 2; 解决办法就是用union替换 ...

  4. [LeetCode] 47. Permutations II 全排列 II

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  5. java:网络编程(UDP (DatagramSocket和DatagramPacket)正则表达式)

    java:网络编程(UDP (DatagramSocket和DatagramPacket)正则表达式) * TCP* 特点:面向连接,点对点的通信,效率较低,但安全可靠* UDP:用户数据报协议,类似 ...

  6. 如何杀死处于进程状态D的进程

    D状态的就是 uninterruptible sleep ,此时进程不能被信号唤醒,GDB等调试工具也不能对它调试,因为GDB也是用到了信号,也杀不死它 D状态的形成 如何分析D状态 cat /pro ...

  7. java静态代理和JDK动态代理

    静态代理 编译阶段就生产了对应的代理类 public interface IBussiness { void execute(); } public class BussinessImpl imple ...

  8. (六)linux 学习 -- 从 shell 眼中看世界

    The Linux Command Line 读书笔记 - 部分内容来自 http://billie66.github.io/TLCL/book/chap08.html 文章目录 字符展开 `*` 路 ...

  9. [基础]C++:名字的作用域

    每个名字都有自己的活动空间,同一个名字在不同的作用域可能指向不同的实体. 作用域:通常是以{}为分隔. 名字的有效区域开始于名字的声明,以声明语句所在的末端为结束. #include<iostr ...

  10. Django 报错 admin.E408 admin.E409 admin.E410

    报错内容 ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MI ...