POST request interface real column

/ **
* HttpPost transmission request
* @param strURL
* service address
* @param the params
* request data
* @param LogIO
* whether the printing O
* @return Success: Returns a string json
*
* /

public static String postJson(String strURL, Object params, boolean logIO) {

log.info ( "requestUrl =" + strURL);
the try {
the URL = new new URL the URL (strURL); // create a connection
the HttpURLConnection Connection = (the HttpURLConnection) URL
.OpenConnection ();
connection.setDoOutput (to true);
connection.setDoInput ( to true);
connection.setUseCaches (to false);
connection.setInstanceFollowRedirects (to true);
connection.setRequestMethod ( "the POST"); // set request mode
connection.setRequestProperty ( "Accept", "application / json"); // set to receive data format
connection.setRequestProperty ( "Content-Type", "application / json; charset = UTF-8"); // set the format of transmission data
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;
}

The catch} (IOException E) {
log.error ( "Exception Occur When HTTP POST Request Send!", E);
}
return "error"; // custom error message
}

Test category

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 ( "specified value:" + token);

}

 

Guess you like

Origin www.cnblogs.com/yhm9/p/11360831.html