新手入门——Java spring发起网络请求(Post,get请求的发送)

一、Post,Get请求方法代码

Spring boot 目录结构
目录结构

package wechatdemo1.demo.service;//包名 调用方法为 import 包名.类名
import com.alibaba.fastjson.JSON;
import java.io.*;
import java.net.*;
import java.util.Map;

public class PostRequest { //类名Postrequest 
    /**
     * 调用接口 post
     * @param apiPath
     */
    public String doGetPost(String apiPath,String type,Map<String,Object> paramMap){
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type) ; // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            //connection.setRequestProperty("Authorization","Basic XXXXXXXXXXXXXX"); //base 64加密 username:password方式。若用不到可注释
            connection.connect();
            if(type.equals("POST")){
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(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;
                }
                result = new String(data, "UTF-8"); // utf-8编码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

二、引入JSON依赖

在pom.XML里添加dependency

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.75</version>
		</dependency>

右下角 Import Changes 后生效

三、调用Post,Get请求

import wechatdemo1.demo.service.*;//改为自己方法所在的package包名
public String cs(){  //改为自己的方法名
	String url="http://xxbnby-1.natapp1.cc/hello";//修改为自己的url
	Postrequest postrequest=new Postrequest();
	Map<String, Object> paramMap = new HashMap<String, Object>();//body 参数
	postrequest.doGetPost(url,"POST",paramMap );//发送请求 POST可以改为GET
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring发送POST请求可以使用以下两种方式: 1. 使用Spring RestTemplate 使用Spring的RestTemplate可以方便地发送POST请求。示例代码如下: ``` RestTemplate restTemplate = new RestTemplate(); String url = "http://example.com/api"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, String> params = new HashMap<>(); params.put("key1", "value1"); params.put("key2", "value2"); HttpEntity<Map<String, String>> request = new HttpEntity<>(params, headers); String result = restTemplate.postForObject(url, request, String.class); ``` 在上述代码中,我们首先创建了一个RestTemplate对象,然后设置了请求的URL和请求头,接着创建了一个Map对象,包含了要发送请求参数。最后,我们使用RestTemplate的postForObject方法发送POST请求,并将结果转换为字符串类型。 2. 使用Spring MVC的Controller 在Spring MVC中,我们可以使用@Controller注解的方法来处理POST请求。示例代码如下: ``` @Controller @RequestMapping("/api") public class MyController { @PostMapping("/myEndpoint") @ResponseBody public String handleRequest(@RequestBody Map<String, String> params) { // 处理请求参数 String result = "Hello, " + params.get("name") + "!"; return result; } } ``` 在上述示例代码中,我们创建了一个MyController类,并使用@PostMapping注解标记了一个处理POST请求的方法。该方法使用@RequestBody注解来接收请求体中的参数,并返回一个字符串类型的结果。通过@ResponseBody注解,我们可以将返回值转换为JSON格式的数据。最后,在@RequestMapping注解中指定了请求的URL。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值