对接第三方接口时,有时接口要求参数为json格式,留个笔记备用!
引入的包如下
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import java.security.MessageDigest;
import org.apache.http.entity.StringEntity
核心代码如下,其中有个对参数进行hash+salt加密方法名为 getSignature()
getSignature()具体代码如下图一
发送请求并获取响应的代码如下图二
private String getSignature(String param) {
String ori=param+指定的salt或者随机生成salt;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
md.update(ori.getBytes("UTF-8"));
return byte2Hex(md.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private String byte2Hex(byte[] bytes){
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i=0;i<bytes.length;i++){
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length()==1){
//1得到一位的进行补0操作
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
HttpClient client = new DefaultHttpClient();
HttpResponse resp;
HttpPost post = new HttpPost(url);
post.addHeader("Accept", "application/json");
String authorization = "Bearer " + getAccessToken().get("data").toString();
post.addHeader("Authorization", authorization);
post.addHeader("Content-Type", "application/json");
JSONObject param = new JSONObject();
param.put("paraName1",paramaValue1);
param.put("paraName2",paramaValue2);
String sign=getSignature(param.toString());
post.addHeader("sign", sign);
StringEntity reqEntity = new StringEntity(param.toString(),"utf-8");
reqEntity.setContentEncoding("UTF-8");
reqEntity.setContentType("application/json");
// 设置类型
// 设置请求的数据
post.setEntity(reqEntity);
try{
resp = client.execute(post);
HttpEntity httpEntity = resp.getEntity();
sResponse = EntityUtils.toString(httpEntity, "UTF-8").trim();
Map<String, Object> respMap =jsonToBean(sResponse, Map.class);
}catech(Exception e){
e.printstsck();
}
resp = client.execute(post);
,httppost设置参数主要靠xxxeneity,详情可以百度查看使用!
文章出处登录后可见!
已经登录?立即刷新