java-HttpURLConnection 发送POST请求 传递参数或JSON数据

需求 三方接口   restful请求  POST方式   参数JSON   接收数据JSON

HttpURLConnection发送POST请求

public class RestUtil {
    public String postMethod(String url,String param){
        // 结果值
        StringBuffer rest=new StringBuffer();
        HttpURLConnection conn=null;
        OutputStream out=null;
        BufferedReader br=null;
        try {
            // 创建 URL
            URL restUrl = new URL(url);
            // 打开连接
            conn= (HttpURLConnection) restUrl.openConnection();
            // 设置请求方式为 POST
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection","keep-Alive");
            // 设置接收文件类型
//            conn.setRequestProperty("Accept","application/json");
            //设置发送文件类型
			 这里注意  传递JSON数据的话 就要设置
			 普通参数的话 就要注释掉
            conn.setRequestProperty("Content-Type","application/json");
            // 输入 输出 都打开
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //开始连接
            conn.connect();
            // 传递参数  流的方式
            out=conn.getOutputStream();
            out.write(param.getBytes());
            out.flush();
            // 读取数据
            br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line=null;
            while (null != (line=br.readLine())){
                rest.append(line);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭所有通道
            try {
                if (br!=null) {
                    br.close();
                if (out!=null) {
                    out.close();
                if (conn!=null) {
                    conn.disconnect();
            } catch (Exception e2) {
                e2.printStackTrace();
        return rest.toString();

客户端请求

 @GetMapping("/getData")
    public String getData() {
        RestUtil restUtil = new RestUtil();
        String IP = "127.0.0.1";
        String url = "http://" + IP + "/server/data";
        String level = "0";
        String dateTime = "2020-10";
        // 参数
        String param;
        // 接收数据
        String result;
         * 第一种   参数为JSON
         * 要打开设置 conn.setRequestProperty("Content-Type","application/json");
        param = "{\"level\":\"" + level + "\",\"dateTime\":\"" + dateTime + "\"}";
        result = restUtil.postMethod(url, param);
         * 第二种  直接传递参数
         * 关闭 conn.setRequestProperty("Content-Type","application/json");
        StringBuffer dataBuffer = new StringBuffer();
        try {
            dataBuffer.append(URLEncoder.encode("level", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(level, "UTF-8"));
            dataBuffer.append("&");
            dataBuffer.append(URLEncoder.encode("dateTime", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(dateTime, "UTF-8"));
            param = dataBuffer.toString();
            result = restUtil.postMethod(url, param);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        //接收的数据
        System.out.println("result==" + result);
        // 然后对 数据 进行 JSON解析
        JSONObject jsonObject = JSON.parseObject(result);
        String code = jsonObject.get("code") == null ? "" : jsonObject.get("code").toString();
        String message = jsonObject.get("message") == null ? "" : jsonObject.get("message").toString();
        dateTime = jsonObject.get("dateTime") == null ? "" : jsonObject.get("dateTime").toString();
        JSONArray dataJsonArray = (JSONArray) jsonObject.get("data");
        if (null != dataJsonArray && dataJsonArray.size() > 0) {
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject data = (JSONObject) dataJsonArray.get(i);
                String account = data.get("account") == null ? "" : data.get("account").toString();
                String name = data.get("name") == null ? "" : data.get("name").toString();
                System.out.println("code==" + code + "++message==" + message + "++dateTime==" + dateTime
                        + "++account==" + account + "++name==" + name);
        return "success";

服务端 如果接收为JSON数据的话 就要从流中取出数据

(2021/6/21新增->不建议这种方法,直接参数加注解 @RequestBody)

	//读取流中的json数据
        BufferedReader br=null;
        StringBuffer result=null;
        try {
            br=new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
            String line=null;
            while (null!=(line=br.readLine())){
                result.append(line);
            System.out.println("接收参数:"+result.toString());
        } catch (Exception e) {
            e.printStackTrace();

服务端 如果是普通参数的话 直接获取

* 如果是参数的方式 String level = request.getParameter("level"); String dateTime = request.getParameter("dateTime");

服务端返回JSON数据

		return "{\"code\":\"100001\",\"message\":\"请求成功\",\"dateTime\":\"2020-10\"," +
                "\"data\":[{\"account\":\"zhangsan\",\"name\":\"张三\"}," +
                "{\"account\":\"lisi\",\"name\":\"李四\"}," +
                "{\"account\":\"wangwu\",\"name\":\"王五\"}," +
                "{\"account\":\"xiaoliu\",\"name\":\"小六\"}]}";

推荐使用第三方库

这里使用的是 hutool , 很方便

		 public static void main(String[] args) {
        // hutool
        // get 请求
        String getRequestStringUrl = "http://localhost:8080/getRequest?id=1";
        HttpRequest.get(getRequestStringUrl).timeout(5 * 60 * 1000).execute();
        // post 请求 传递json参数
        String postRequestStringUrl = "http://localhost:8080/postRequest";
        // 参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data","123");
        jsonObject.put("email","123456@163.com");
        // 设置请求头
        Map<String, String > heads = new HashMap<>();
        heads.put("Content-Type", "application/json;charset=UTF-8");
        // 纯请求  要结果的话 最后加 .body()
        HttpRequest.post(postRequestStringUrl) // url
                .headerMap(heads, false) // 请求头设置
                .body(jsonObject.toJSONString()) // json参数
                .timeout(5 * 60 * 1000) // 超时
                .execute(); // 请求
                // .body(); // 返回值
                    java-HttpURLConnection 发送POST请求  传递参数或JSON数据需求 三方接口   restful请求  POST方式   参数JSON   接收数据JSONHttpURLConnection发送POST请求public class RestUtil {    public String postMethod(String url,String param){        // 结果值        StringBuffer rest=new StringBuffe
				
之前的文章介绍过通过报文的方式HttpURLConnection提交post请求,今天介绍下通过Json参数的方法提交Post请求,先上代码 public static HttpResponse sendPost(String url, String param, Charset charset) { try { URL httpurl...
private void sendData(String url, String jsonDataStr) { HttpURLConnection conn = null; OutputStreamWriter out = null;
HttpURLConnection 今天写了个http客户端,代码很简单,网上的资料也一大堆。我从网上copy一份HttpURLConnection就开始测试,测试的时候发现每次都返回给我500。 String urlString = "***"; String params = "{****}"; URL url; try { url = new URL(urlString);
分别给出了post发送文件和json数据的函数,其中使用到了Jackson库来转化Json数据,使用log4j2来打印日记,可自行剔除。 public class HttpUtils { static private ObjectMapper objectMapper=new ObjectMapper(); static private Logger logger= LogMana...
我们在开发的使用,直接使用的开源框架,例如:Xutil,Volley开源框架直接访问网络,但是我们也需要知道其中的一些知识,了解一下怎样访问网络的。下面我们模拟以下客户端和服务端,看看POST。 首先看POST线程类的定义 class PostThread extends Thread { private String name; private String age; private TextView show_content; private St...
现在涉及到第三方对接方面功能时很多第三方平台为了安全使用的都是https请求,传统的发起http请求的方法就不再适用了,但使用原生的URLConnection方法来进行调用效果确是非常不错的,接下来就来介绍一下它的使用方法。 String url = "https://xxx-你的请求地址"; URL serverUrl = new URL(url); HttpURLConnection conn = (Http
HttpHttpURLConnection-POST发送文件请求概述常见的Content-Type类型POST请求POST请求(文件+参数) 本文章只编写http使用HttpURLConnection发送post请求,包括两方面 1、普通post请求() 2、带有参数和文件的post请求 常见的Content-Type类型 1、application/x-www-form-urlencoded 最常见的 POST 提交数据的方式,原生Form表单,默认为application/x-www-form-
import com.alibaba.fastjson.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apa...
java - HttpURLConnection 发送post请求 最近在做访问第三方接口的模块,虽然之前做过,而且有很多工具类的支持,但是我也遇到了一个让我痛苦了半天的‘坑’ 首先先上最终好使并实现的代码: public static String postJson(String requestUrl, String params) throws Exception { System.out...
import com.alibaba.fastjson.JSON; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; * @Autho. import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpPostExample { private final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { HttpPostExample http = new HttpPostExample(); System.out.println("Testing 1 - Send Http POST request"); http.sendPost(); // HTTP POST request private void sendPost() throws Exception { String url = "http://www.example.com"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "param1=value1&param2=value2"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); in.close(); //print result System.out.println(response.toString());