Java实现post请求(带有参数)

package Sort.pay;

import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class Pay {
    public static void main(String[] args) {
        String url = "http://xxxxxx";//访问路径
        Random random = new Random();
        Map<String, Object> map = new HashMap<>();
        map.put("authCode", "1423009170000001");
        map.put("resource", "api.hl.order.pay.unified");
        map.put("requestTime", "20230129105758");
        map.put("versionNo", "1");
        Map<String, Object> params = new HashMap<>();
        params.put("businessOrderNo", random.nextInt(1000000000));//202105623000002
        params.put("payAmount", "90.00");
        params.put("remark", "购买山核桃20斤");
        params.put("merchantNo", "771389");
        params.put("operatorAccount", "19884151060");
        params.put("deviceNo", "402102317000001");
        params.put("notifyUrl", "http://testapi.liankok.com/notify/pay");
        params.put("payExpireTime", "600");
        params.put("limitPay", "1");
        params.put("payUrlExpireTime", "60");
        params.put("subject", "山核桃");
        params.put("goodsTag", "guolicheng");
        params.put("goodsInfo", "{\"receiptid\":\"323323\",\"costprice\":200.00,\"goodsdetail\":[{\"goodsid\":\"123123123\",\"goodsname\":\"小石头\",\"thirdgoodsid\":\"23323453\",\"quantity\":1,\"price\":5.00}]}");
        map.putAll(params);
//            map.put("params",params);
        //排序集合
        map = PaySortUtil.sortByKey(map);
        //遍历输出拼接字符串
        Set<String> keys = map.keySet();
        String str = "";
        for (String key : keys) {
            str += key + "=" + map.get(key) + "&";
        }
        str = str.toLowerCase() + "U7iIPg2x1k";
        //md5加密字符串
        String md5sr = DigestUtils.md5Hex(str);
        map.put("sign", md5sr);
        Map<String, Object> map3 = new HashMap<>();//存放结果
        //将需要比较删除的两个集合添加
        map3.putAll(map);
        map3.putAll(params);
        //for - each遍历比较且删除
        for (String a : map.keySet()) {
            if (params.containsKey(a) || params.containsValue(map.get(a))) {
                map3.remove(a);
            }
        }
        map3.put("versionNo", "1");
        map3.put("params", params);
        System.out.println(map3);

        JSONObject jsonObject=JSONObject.fromObject(map3);
        System.out.println(jsonObject.toString());

       String ss= Pay.sendPost(url,jsonObject.toString());
        System.out.println(ss);
    }


    public static String sendPost(String url,String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.err.println("发送POST请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

}
class PaySortUtil {
    public static Map<String, Object> sortByKey(Map<String, Object> map){
        //创建一个带有比较器的TreeMap
        Map<String, Object> treeMap = new TreeMap<>(String::compareTo);
        //将你的map传入treeMap
        treeMap.putAll(map);
        return treeMap;
    }
}

pom文件所需依赖,有些依赖不是必需的,这里没有删除

 <dependencies>
<!--        post请求的依赖-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>16.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>
        <!--MD5依赖-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.surefire</groupId>
            <artifactId>maven-surefire-common</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>org.kie.modules</groupId>
            <artifactId>org-apache-commons-httpclient</artifactId>
            <version>6.2.0.CR2</version>
            <type>pom</type>
        </dependency>

        <!-- JSONObject对象依赖的jar包 -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.2.3</version>
            <classifier>jdk15</classifier><!-- 指定jdk版本 -->
        </dependency>
        <!-- Json依赖架包下载 -->
    </dependencies>

    <properties>
        <maven.compiler.source>7</maven.compiler.source>
        <maven.compiler.target>7</maven.compiler.target>
    </properties>
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用 Java 的 HttpURLConnection 类来发送 POST 请求带有参数。以下是一个简单的示例代码: ```java import java.io.*; import java.net.*; public class PostRequest { public static void main(String[] args) throws Exception { // 设置请求的URL URL url = new URL("http://example.com/api"); // 创建连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setDoOutput(true); // 设置参数 String params = "param1=value1&param2=value2"; OutputStream outputStream = connection.getOutputStream(); outputStream.write(params.getBytes("utf-8")); outputStream.flush(); outputStream.close(); // 发送请求并获取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应 System.out.println(response.toString()); } } ``` 在上面的示例代码中,我们使用 HttpURLConnection 类来发送 POST 请求并设置了请求的 Content-Type 为 application/x-www-form-urlencoded,这是一种常见的 POST 请求的 Content-Type。然后我们设置了参数,将参数写入到连接的输出流中,并发送请求。最后我们从连接的输入流中读取响应内容并输出。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值