JAVA模拟post方式提交URL参数和body内json参数

package test.itsm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.com.tron.omms.util.JsonUtil;

public class HttpRequest {

    public static void main(String[] args) throws Exception {

        String strURL = "http://localhost:8080/console/useradd.sess?a=appid&t=1&s=signature&d=digest";
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put("loginname", "zhangsan");
        paramMap.put("username", "张三");
        paramMap.put("passwd", "passcode01");
        paramMap.put("status", "0");

        OutputStreamWriter out = null;
        InputStream is = null;
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(JsonUtil.object2json(paramMap));
            out.flush();
            out.close();

            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                System.out.println("主机返回:" + result);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
阅读更多
版权声明:Life's tragedy is that we get old too soon and wise too late. https://blog.csdn.net/Love_Legain/article/details/80352161
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭