JAVA后端向自己发送POST请求

发送请求的方法

public void toposttest(@RequestParam Integer devid,@RequestParam Integer caseid){
        String params = "?none=&devid=" + devid + "&caseid=" + caseid;
        String url = "api/localapi/getmany";
        String str = PostUtil.updateDev(url, params);
        //json字符串转json对象
        JSONObject jsonHm = JSON.parseObject(str);
        //json字符串转list实体类,
        List<TsChannel> tss = JSON.parseArray(jsonHm.get("data").toString(),TsChannel.class);
    }

转发请求的类

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class PostUtil {
    private static String local = "http://127.0.0.1:80/";
    
    public static String updateDev(String url, String params) {
        String result = sendPostUrl(local + url, params);
        return result;
    }

    /**
     * 在后端发送post请求给自己 sendUrl (远程请求的URL) param (远程请求参数) JSONObject (远程请求返回的JSON)
     */
    private static String sendPostUrl(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据(设置返回数据编码为UTF-8)
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}
Controller层的接收方法
@Slf4j
@Controller
@RequestMapping("api/localapi")
public class LocalApiController {
    @Autowired
    ChannelService channelService;

    @RequestMapping("getmany")
    @ResponseBody
    public Result selectmany(Channel channel) {
        List<Channel> l = channelService.selectmany(channel.getDevid());
        return r.result("0001", l, "请求成功");
    }
}

注意:当发送参数 的值中有"&"字符时,参数中的"&"及后面的字符串会被截掉

解决方法:

使用replace("&","#")把"&"字符替换成其他字符,在接收端再转回来replace("#","&")

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java后端发送HttpPost请求的步骤如下: 1. 创建HttpClient对象。 2. 创建HttpPost对象,并设置请求的URL。 3. 设置请求参数,可以使用NameValuePair或者HttpEntity。 4. 执行请求,获取HttpResponse对象。 5. 解析HttpResponse对象,获取响应结果。 具体实现可以参考以下代码: ``` import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpPostExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://example.com/api"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { String response = EntityUtils.toString(httpEntity); System.out.println(response); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值