栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

请求测试:




引用POM:


		  	org.json
		  	json
		 	20180130

代码实现:

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;


@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();
            }
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/907994.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号