使用java写GET和POST请求调用接口

使用java写GET和POST请求调用接口

1.GET请求

/**
     * 发起请求
     * @param path
     * @param param
     * @return
     */
    public static String getRequest(String path, String param) {
        String returnData = "";
        //url拼接
        String srtUrl = path + "?" + param;
        try{
            URL url = new URL(srtUrl);
            //打开和url之间的连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

            //请求头
            urlConn.setRequestProperty("Accept-Charset", "utf-8");
            urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            urlConn.setDoOutput(true);
            urlConn.setDoInput(true);
            urlConn.setRequestMethod("GET");//GET和POST必须全大写
            urlConn.connect();

            int code = urlConn.getResponseCode();//获得响应码
            if(code == 200) {//响应成功,获得响应的数据

                //解决中文乱码
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));

                //解决返回参数换行问题,一次读一行,读入null时文件结束
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    returnData += tempString;
                }
                reader.close();

            }
            urlConn.disconnect();   //断开连接

        }catch (Exception e) {
            e.printStackTrace();
        }

        return returnData;
    }

2.POST请求

/**
     * 发起请求
     * @param path
     * @param param
     * @return
     */
    public static String postRequest(String path, String param) {
        String returnData = "";
        //url拼接
        String srtUrl = path + "?" + param;

        int responseCode;

        try {
            URL restURL = new URL(srtUrl);
            HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
            conn.setRequestMethod("POST");
            //请求头
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setDoOutput(true);

            //解决中文乱码
            OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            os.write(param);
            os.flush();
            // 输出response code
            responseCode = conn.getResponseCode();
            // 输出response
            if (responseCode == 200) {
                //解决中文乱码
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                //解决返回参数换行问题,一次读一行,读入null时文件结束
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    returnData += tempString;
                }
                reader.close();

            } else {
                returnData = "false";
            }
            // 断开连接
            os.close();
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnData;
    }

3.举例调用

		//发起GET请求
        String getUrl = "your_url";//接口地址
        String getParam = "key1=" + "value1" + "&" + "key2=" + "value2" ;//拼接参数
        String get = getRequest(getUrl,getParam);
        //将返回参数转为json格式
        //转化为json格式时需要throws JSONException异常
        JSONObject getJson = new JSONObject(get);
        //获取location中的name的值
        getJson.getJSONObject("location").get("name").toString();

//		举例返回参数json格式为如下:
//        {
//            "location":
//            {
//                "name":"New York",
//                "country":"United States",
//                "region":"New York"
//            },
//            "current":
//            {
//                "temperature":25,
//                "humidity":65,
//                "wind_speed":15
//            },
//            "date":"2023-08-16 20:30:33"
//        }


        //发起POST请求
        String postUrl = "your_url";//接口地址
        String postParam = "key1=" + "value1" + "&" + "key2=" + "value2" ;//拼接参数
        String post = postRequest(postUrl,postParam);
        //将返回参数转为json格式
        //转化为json格式时需要throws JSONException异常
        JSONObject postJson = new JSONObject(post);
        //获取date的值
        postJson.get("date").toString();

4.需要引用的jar包

		//转化为json格式时需要throws JSONException异常
		import org.json.JSONException;
		import org.json.JSONObject;
		import java.io.BufferedReader;
		import java.io.InputStreamReader;
		import java.io.OutputStreamWriter;
		import java.net.HttpURLConnection;
		import java.net.URL;
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值