首页 前端知识 java 使用httppost设置json参数发送请求

java 使用httppost设置json参数发送请求

2024-05-07 13:05:45 前端知识 前端哥 729 985 我要收藏

对接第三方接口时,有时接口要求参数为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,详情可以百度查看使用!

转载请注明出处或者链接地址:https://www.qianduange.cn//article/7392.html
标签
评论
发布的文章

Pycharm创建json文件类型

2024-05-12 00:05:50

C#Post请求,带json参数。

2024-05-12 00:05:28

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!