自学内容网 自学内容网

HttpUtil的get和post请求

Http工具类 

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * http 工具类
 */
public class HttpUtil {
    private static String contentType = "application/json";

    private static String encoding = "UTF-8";
     
 /**
     * post请求
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, String params){
        try {
            return postGeneralUrl(url, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "请求失败";
    }
    public static String postGeneralUrl(String generalUrl, String params)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setConnectTimeout(2000);
        connection.setDoInput(true);
        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();
        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }


    public static String uploadFile(String url, File file, Map<String, Object> map) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        //每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
        String boundary ="--------------4585696313564699";
        try {
            //文件名
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(url);
            //设置请求头
            httpPost.setHeader("Content-Type","multipart/form-data; boundary="+boundary);
            //HttpEntity builder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //字符编码
            builder.setCharset(Charset.forName("UTF-8"));
            //模拟浏览器
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //boundary
            builder.setBoundary(boundary);
            //multipart/form-data
            builder.addPart("file",new FileBody(file));
            builder.addTextBody("needVerify",map.get("needVerify").toString());
            builder.addTextBody("businessTimestamp",map.get("businessTimestamp").toString());
            builder.addTextBody("nonce",map.get("nonce").toString());
            builder.addTextBody("businessSign",map.get("businessSign").toString());
            //HttpEntity
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            HttpResponse response = httpClient.execute(httpPost);
            //响应
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String get(TreeMap<String, Object> map, String url){
        //1、创建httpClient
        CloseableHttpClient client = HttpClients.createDefault();
        //2、封装请求参数
        List<BasicNameValuePair> list = new ArrayList<>();
        map.forEach((k,v)->
                list.add(new BasicNameValuePair(k, v.toString()))
                );
        //3、转化参数
        String params ;
        String result = null;
        CloseableHttpResponse response = null;
        try {
            params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            //4、创建HttpGet请求
            HttpGet httpGet = new HttpGet(url+ "?"+ params);
            System.out.println("请求URL: "+httpGet);
            response = client.execute(httpGet);
            //5、获取实体
            HttpEntity entity = response.getEntity();
            //将实体装成字符串
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

对象转换为json字符串

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Json工具类.
 */
public class GsonUtils {
    private static Gson gson = new GsonBuilder().create();

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static <T> T fromJson(String json, Class<T> classOfT) throws JsonParseException {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T fromJson(String json, Type typeOfT) throws JsonParseException {
        return (T) gson.fromJson(json, typeOfT);
    }

post请求

public static void main(String[] args) {
        User user= new User();
        user.setName("张三");
        // 1.转化参数
        String param = GsonUtils.toJson(user);
        // 2.发送请求
        String url = "";
        String result = HttpUtil.post(url, param);
        // 3.获取结果
        System.out.println("响应结果: "+ result);
    }

get请求

 public static void main(String[] args) {
        // 1.组装参数
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("name", "张三");
        map.put("id", "1");
        map.put("idCard", "51090102198801025878");
        // 2.签名 无签名可以忽略
       // String businessSign = SignUtil.sign(map, key);
        map.put("businessSign", "签名字符串");
        // 3.发送请求
        String url = "";
        String result = HttpUtil.get(map, url);
        // 4.获取结果
        System.out.println("响应结果: "+ result);
    }

如果需要签名

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;


public class MD5Encoder {
    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b",
            "c", "d", "e", "f"};

    public static String encode(String rawPass, String salt) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            // 加密后的字符串
            result = byteArrayToHexString(md.digest(
                    mergePasswordAndSalt(rawPass, salt)
                            .getBytes(StandardCharsets.UTF_8)));
        } catch (Exception ex) {
        }
        return result;
    }

    private static String mergePasswordAndSalt(String password, String salt) {
        if (password == null) {
            password = "";
        }
        if ((salt == null) || "".equals(salt)) {
            return password;
        } else {
            return password + salt;
        }
    }

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 16进制字串
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.thinkgem.jeesite.modules.panelmachine.request.OpenAPIRequest;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;


public class SignUtil {

    public static String signJsonObject(JsonObject jsonObject, String signKey, int floor) {
        List<String> keys = new ArrayList<>();
        HashMap<String, String> params = new HashMap<>();
        for (Map.Entry<String, JsonElement> entity : jsonObject.entrySet()) {
            String key = entity.getKey();
            String value = "";
            if (entity.getValue().isJsonNull()) {
                continue;
            }
            if (entity.getValue().isJsonObject()) {
                value = signJsonObject(entity.getValue().getAsJsonObject(), signKey, floor + 1);
            } else if (entity.getValue().isJsonArray()) {
                List<String> result = new ArrayList<>();
                entity.getValue().getAsJsonArray().forEach(action -> {
                    if (action.isJsonObject()) {
                        result.add(signJsonObject(action.getAsJsonObject(), signKey, floor + 1));
                    } else if (action.isJsonArray()) {
                        result.add(signJsonObject(action.getAsJsonArray().getAsJsonObject(), signKey, floor + 1));
                    } else {
                        result.add(action.getAsString());
                    }
                });
                if (result.size() > 0) {
                    Collections.sort(result);
                    StringBuilder sb = new StringBuilder();
                    result.forEach(action -> {
                        if(StringUtils.hasText(action)) {
                            sb.append(action + "&") ;
                        } ;
                    });
                    sb.deleteCharAt(sb.length() - 1);
                    value = MD5Encoder.encode(sb.toString(), "");
                }
            } else {
                value = entity.getValue().getAsString();
            }
            if (StringUtils.isEmpty(value)) {

            } else {
                keys.add(key);
                params.put(key, value);
            }
        }
        if (keys.size() == 0) {
            return "";
        }
        // checkSign
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();

        keys.forEach(key -> sb.append(key + "=" + params.get(key) + "&"));
        if (floor == 1 && StringUtils.hasText(signKey)) {
            sb.append("key=" + signKey);
        } else {
            sb.deleteCharAt(sb.length() - 1);
        }
        System.out.println("签名前字符串:"+ sb.toString());
        System.out.println("签名结果:"+MD5Encoder.encode(sb.toString(), ""));
        return MD5Encoder.encode(sb.toString(), "");
    }

    public static OpenAPIRequest sign(OpenAPIRequest openAPIRequest, String key) {
        openAPIRequest.setNonce(UUID.randomUUID().toString());
        openAPIRequest.setBusinessTimestamp(System.currentTimeMillis()+"");
        openAPIRequest.setBusinessSign(md5Sign(openAPIRequest,key));
        return openAPIRequest ;
    }

    public static OpenAPIRequest sign(OpenAPIRequest openAPIRequest, Map<String, String> params, String key) {
        openAPIRequest.setNonce(UUID.randomUUID().toString());
        openAPIRequest.setBusinessTimestamp(System.currentTimeMillis()+"");
        openAPIRequest.setBusinessSign(md5Sign(openAPIRequest , params, key));
        return openAPIRequest ;
    }

    public static  String md5Sign(OpenAPIRequest request, Map<String, String> params, String key) {
        JsonObject jsonObject = new JsonParser().parse(new Gson().toJson(request)).getAsJsonObject();
        params.entrySet().forEach(action -> jsonObject.addProperty(action.getKey() , action.getValue()));
        return signJsonObject(jsonObject, key,1) ;
    }

    private static String md5Sign(OpenAPIRequest request, String key) {
        JsonObject jsonObject = new JsonParser().parse(new Gson().toJson(request)).getAsJsonObject();
        jsonObject.remove("image");
        return signJsonObject(jsonObject, key ,1) ;
    }

    public static String sign(TreeMap<String, Object> map, String key) {
        StringBuilder sb = new StringBuilder();
        map.forEach((k,v)->{
            sb.append(k + "=" + v + "&");
        });
        sb.append("key=" + key);
        System.out.println("签名前字符串: "+ sb);
        String businessSign = MD5Encoder.encode(sb.toString(), "");
        System.out.println("签名结果: " + businessSign);
        return businessSign;
    }

签名调用方式

//可以更改为配置或者写死 
public static final String KEY = "key"; 

public static void main(String[] args) {
//封装参数
TreeMap<String, Object> map = new TreeMap<>();
        map.put("name", "张三");
        map.put("id", "1");
        map.put("idCard", "51090102198801025878");
// 签名
 String businessSign = SignUtil.sign(map, key);

 }


原文地址:https://blog.csdn.net/man_18483633325/article/details/144339960

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!