java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java实现post请求

Java实现post请求详细代码(带有参数)

作者:FJ.

这篇文章主要给大家介绍了关于Java实现带有参数post请求的相关资料,文中通过代码示例介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友可以参考下

代码示例:

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>

附:java使用post请求带参(放在body中)访问外部连接

java使用post请求带参(放在body中)访问外部连接

package com.bxzn.bxgd.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxzn.bxgd.util.yuntai.HTTPClientUtil;
import com.bxzn.bxgd.util.yuntai.HttpsClientUtil;
import netscape.javascript.JSObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("create_time", checkLog.getCreateTime());
                jsonObject.put("camera_loc", checkLog.getCameraLoc());
                jsonObject.put("state", checkLog.getState());
                jsonObject.put("type", checkLog.getType());
                jsonObject.put("attach_file", checkLog.getAttachFile());
                jsonObject.put("level", checkLog.getLevel());
                HTTPClientUtil.sendPost(urls, null, JSON.toJSONString(jsonObject));

HTTPClientUtil类

package com.bxzn.bxgd.util.yuntai;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxzn.bxgd.util.socket.WebSocket;
import com.bxzn.bxgd.util.socket.WssSocket;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import javax.sound.sampled.*;
import javax.sql.rowset.serial.SerialBlob;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.sql.Blob;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
/**
 * 和云台进行http的连接
 *
 * @author xxy
 */
public class HTTPClientUtil {
    /**
     * 编码格式。发送编码格式统一用UTF-8
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 设置连接超时时间,单位毫秒。
     */
    private static final Integer CONNECT_TIMEOUT = 6000;
    /**
     * 请求获取数据的超时时间(即响应时间),单位毫秒。
     */
    private static final Integer SOCKET_TIMEOUT = 6000;
    /**
     * @param url  请求地址
     * @param data 只支持JSON对象(com.alibaba.fastjson.JSONObject)
     * @return String
     * @Title:POST请求
     * @Decription:发送POST请求,data参数只支持JSON对象(com.alibaba.fastjson.JSONObject)
     */
    public static String sendPost(String url, Map<String, String> header, JSONObject data) throws IOException {
        // 设置默认请求头
        Map<String, String> headers = new HashMap<>();
        if (header != null) {
            headers = header;
        } else {
            headers.put("Content-Type", "application/json;charset=utf-8");
        }
        return doPostByJSON(url, headers, data, ENCODING);
    }
    /**
     * @param url  请求地址
     * @param data 只支持JSON对象(com.alibaba.fastjson.JSONObject)
     * @return String
     * @Title:POST请求
     * @Decription:发送POST请求,data参数只支持JSON对象(com.alibaba.fastjson.JSONObject)
     */
    public static String sendPost(String url, Map<String, String> header, String data) throws IOException {
        // 设置默认请求头
        Map<String, String> headers = new HashMap<>();
        if (header != null) {
            headers = header;
        } else {
            headers.put("Content-Type", "application/json;charset=utf-8");
        }
        return doPostByJSON(url, headers, JSONObject.parseObject(data), ENCODING);
    }
    /**
     * @param url     请求地址
     * @param headers Map集合的请求头参数
     * @param params  Map集合(输入参数为JSON对象)
     * @return String
     * @Title POST请求(默认编码:UTF-8)
     */
    public static String sendPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        // 将map转成json
        JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
        return doPostByJSON(url, headers, data, ENCODING);
    }
    /**
     * @param url      请求地址
     * @param headers  请求头
     * @param data     请求实体
     * @param encoding 字符集
     * @return String
     * @throws IOException
     * @Title: sendPost
     * @Description: TODO(发送post请求)
     */
    private static String doPostByJSON(String url, Map<String, String> headers, JSONObject data, String encoding) throws IOException {
        // 请求返回结果
        String resultJson = null;
        // 创建Client
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送请求,返回响应对象
        CloseableHttpResponse response = null;
        // 创建HttpPost对象
        HttpPost httpPost = new HttpPost();
        /**
         * setConnectTimeout:设置连接超时时间,单位毫秒。
         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
         * 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        try {
            // 设置请求地址
            httpPost.setURI(new URI(url));
            // 设置请求头
            packageHeader(headers, httpPost);
            // 设置实体
            httpPost.setEntity(new StringEntity(JSON.toJSONString(data), encoding));
//            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            // 发送请求,返回响应对象
            response = client.execute(httpPost);
            // 获取响应状态
            int status = response.getStatusLine().getStatusCode();
            if (status != HttpStatus.SC_OK) {
                System.out.println("响应失败,状态码:" + status);
            }
            // 获取响应结果
            resultJson = EntityUtils.toString(response.getEntity(), encoding);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, client);
        }
        return resultJson;
    }
    /**
     * Description: 封装请求头
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    /**
     * Description: 释放资源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

然后自己写个测试类就行,顺便一提,HTTPClientUtil.sendPost(urls, null, JSON.toJSONString(jsonObject));这个方法返回值取决于服务器的返回值,是字符串类型

总结 

到此这篇关于Java实现post请求的文章就介绍到这了,更多相关Java实现post请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文