其他分享
首页 > 其他分享> > POST请求接口实列

POST请求接口实列

作者:互联网

/**
* 发送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"; // 自定义错误信息
}

测试类

@Test

public void testPostInteface(){

String resutl=HttpRequestUtil.postJson(url, json,true);
JSONObject str=JSONObject.parseObject(resutl);
String value=str.getString("data");

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

}

 

标签:String,接口,实列,connection,new,POST,inputJson,out,log
来源: https://www.cnblogs.com/yhm9/p/11360831.html