java.net.HttpURLConnection发送POST、GET请求

请求测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
引用POM:

<dependency>
		  	<groupId>org.json</groupId>
		  	<artifactId>json</artifactId>
		 	<version>20180130</version>
</dependency>

代码实现:

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/*
 * @author 在下令狐
 * @describe
 * @date 2020/10/17
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value="/doPostData",produces="application/json;charset=utf-8")
    public void doPostData(HttpServletRequest request, HttpServletResponse response) throws IOException {

        StringBuffer stringBuffer = new StringBuffer();

        InputStream inputStream = request.getInputStream();
        String strLine = "";
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        while (null != (strLine = bufferedReader.readLine())) {
            stringBuffer.append(strLine);
        }
        bufferedReader.close();

        System.out.println("Post request " + stringBuffer.toString());

        Map map = new HashMap<>();
        map.put("status", "success");
        map.put("method", "post");
        map.put("time", System.currentTimeMillis());

        org.json.JSONObject jsonObject = new org.json.JSONObject(map);
        response.getWriter().write(jsonObject.toString());
    }

    @RequestMapping(value="/doGetData",produces="application/x-www-form-urlencoded;charset=utf-8")
    public void doGetData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String age = request.getParameter("age");

        System.out.println("Get request name " + name  + "  age : " + age);

        Map map = new HashMap<>();
        map.put("status", "success");
        map.put("method", "get");
        map.put("time", System.currentTimeMillis());

        org.json.JSONObject jsonObject = new org.json.JSONObject(map);

        response.getWriter().write(jsonObject.toString());
    }

    @RequestMapping(value="/doGetTest",produces="application/x-www-form-urlencoded;charset=utf-8")
    public void doGetTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpURLConnection httpURLConnection = null;
        String host = "http://localhost:8580/test/doGetData";

        try {
            String param = "?name=jack&age=20";

            URL url = new URL(host + param);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            //设置超时时间
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(10000);
            //设置是否从httpURLConnection读入
            httpURLConnection.setDoInput(true);
            //设置是否向httpURLConnection输出
            httpURLConnection.setDoOutput(true);
            //设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("GET");
            //设置此 httpURLConnection 实例是否应该自动执行 HTTP 重定向
            httpURLConnection.setInstanceFollowRedirects(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpURLConnection.connect();

            //得到响应状态码的返回值 responseCode
            int responseCode = httpURLConnection.getResponseCode();

            if (HttpStatus.SC_OK == responseCode) {
                StringBuffer stringBuffer = new StringBuffer();

                InputStream inputStream = httpURLConnection.getInputStream();
                String strLine = "";
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                while (null != (strLine = bufferedReader.readLine())) {
                    stringBuffer.append(strLine);
                }
                bufferedReader.close();

                System.out.println("Get请求成功,响应状态码 :" + responseCode + " 返回数据 :" + stringBuffer.toString());
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpURLConnection) {
                //断开连接
                httpURLConnection.disconnect();
            }
        }
    }

    @RequestMapping(value="/doPostTest",produces="application/x-www-form-urlencoded;charset=utf-8")
    public void doPostTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpURLConnection httpURLConnection = null;
        String host = "http://localhost:8580/test/doPostData";
        org.json.JSONObject jsonObject = new org.json.JSONObject();

        try {
            jsonObject.put("name", "jack");
            jsonObject.put("age", "20");

            URL url = new URL(host);
            httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setReadTimeout(10000);
            //设置是否向httpURLConnection输出
            httpURLConnection.setDoOutput(true);
            //设置是否从httpURLConnection读入
            httpURLConnection.setDoInput(true);
            //设置是否使用缓存
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            //设置使用标准编码格式编码参数的名-值对
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8");
            outputStreamWriter.write(jsonObject.toString());
            outputStreamWriter.flush();
            outputStreamWriter.close();

            //得到响应状态码的返回值 responseCode
            int responseCode = httpURLConnection.getResponseCode();

            if (HttpStatus.SC_OK == responseCode) {
                StringBuffer stringBuffer = new StringBuffer();

                InputStream inputStream = httpURLConnection.getInputStream();
                String strLine = "";
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

                while (null != (strLine = bufferedReader.readLine())) {
                    stringBuffer.append(strLine);
                }
                bufferedReader.close();

                System.out.println("Post请求成功,响应状态码 :" + responseCode + " 返回数据 :" + stringBuffer.toString());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != httpURLConnection) {
                //断开连接
                httpURLConnection.disconnect();
            }
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值