Java向指定Url带参数发送数据(post)

33 篇文章 1 订阅
3 篇文章 0 订阅

代码及注释:
package com.jxctdzkj.cloudplatform.util;

import com.alibaba.fastjson.JSONObject;
import com.jxctdzkj.cloudplatform.bean.DeviceBean;
import com.jxctdzkj.cloudplatform.bean.VillageBean;
import com.jxctdzkj.cloudplatform.config.DateCommon;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**

  • @author Sure

  • @date 2020/10/19 19:19
    */
    @Component
    @EnableScheduling
    public class TaskSchedu {
    @Autowired
    Dao dao;
    @Scheduled(fixedDelay = 1000 *10)
    public void testByTenantId() throws Exception {

     List<VillageBean> list=dao.query(VillageBean.class, Cnd.where("del","=",0));
     //for循环是我遍历数据用的,可以忽略
     for (int i=0;i<list.size();i++){
         String defURL = " 这里是指定的url,因为是政府平台我就不放了";
         URL url = new URL(defURL);
         // 打开和URL之间的连接
         HttpURLConnection con = (HttpURLConnection)url.openConnection();
         con.setRequestMethod("POST");//请求post方式
         con.setUseCaches(false); // Post请求不能使用缓存
         con.setDoInput(true);// 设置是否从HttpURLConnection输入,默认值为 true
         con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出,默认值为 false
    
         //设置header内的参数 connection.setRequestProperty("健, "值");
         con.setRequestProperty("Content-Type", "application/json");
         con.setRequestProperty("isTree", "true");
         con.setRequestProperty("isLastPage", "true");
    
         JSONObject param = new JSONObject();
         String[] data=dao.fetch(DeviceBean.class,Cnd.where("Ncode","=",list.get(i).getDeviceNumber())).getData().split("\\|");
         //参数
         param.put("monitorname", list.get(i).getName());
         param.put("addr", list.get(i).getAddress());
         param.put("longitude", list.get(i).getPosition().split(",")[0]);
         param.put("latitude", list.get(i).getPosition().split(",")[1]);
         param.put("linkman", list.get(i).getPrincipal());
         param.put("phone", list.get(i).getTel());
         System.out.println("data====="+data);
         //不同的数据长度,最大是6位
         for (int j=0;j<data.length;j++){
             if(j==0){
                 param.put("temperature",data[0]);
             }
        if (j==1){
            param.put("humidity", data[1]);
        }
    
             if (j==2){ param.put("carbondioxide", data[2]);}
             if (j==3){  param.put("winddirection", data[3]);}
             if (j==4){
                 param.put("windspeed", data[4]);
             }
         if (j==5){
             param.put("illuminance", data[5]);
         }
         }
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
         System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
         param.put("pushdate",df.format(new Date()));
    
    
    
         //设置body内的参数,put到JSONObject中
    
         System.out.println(param);
    
         // 建立实际的连接
         con.connect();
    
         // 得到请求的输出流对象
         OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(),"UTF-8");
         writer.write(param.toString());
         writer.flush();
    
         // 获取服务端响应,通过输入流来读取URL的响应
         InputStream is = con.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
         StringBuffer sbf = new StringBuffer();
         String strRead = null;
         while ((strRead = reader.readLine()) != null) {
             sbf.append(strRead);
             sbf.append("\r\n");
         }
         reader.close();
    
         // 关闭连接
         con.disconnect();
    
         // 打印读到的响应结果
         System.out.println("运行结束:"+sbf.toString());
    
     }
    

    }
    }

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection类来发送POST请求,具体步骤如下: 1. 创建URL对象,指定要访问的URL地址。 2. 调用URL对象的openConnection()方法,返回一个URLConnection对象。 3. 将URLConnection对象强制转换为HttpURLConnection对象。 4. 设置请求方法为POST,调用setRequestMethod()方法。 5. 设置请求头信息,调用setRequestProperty()方法。 6. 设置请求体信息,调用getOutputStream()方法获取输出流,将请求参数写入输出流。 7. 发送请求,调用getInputStream()方法获取输入流,读取服务器返回的数据。 8. 关闭输入流和输出流,断开连接。 示例代码如下: ``` import java.io.*; import java.net.*; public class HttpPost { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://www.example.com"); // 打开连接 URLConnection connection = url.openConnection(); // 强制转换为HttpURLConnection对象 HttpURLConnection httpURLConnection = (HttpURLConnection) connection; // 设置请求方法为POST httpURLConnection.setRequestMethod("POST"); // 设置请求头信息 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length())); // 设置请求体信息 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(data.getBytes()); outputStream.flush(); outputStream.close(); // 发送请求 InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); inputStream.close(); // 断开连接 httpURLConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,data为请求参数,可以根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值