使用HttpURLConnection发送POST/GET请求并解析返回值

目录

一. Post发送方式

1. 封装请求参数:

2. 填写发送路径:

3.将sendMap,sendUrl 传入到 doPost() 方法中 

4. 解析stringBulider返回值

二. Get发送方式

1.将所有参数封装在sendUrl路径上

2. 将sendUrl参数传入doGet() 方法

3. 解析stringBuffer返回值


注:本文中的 doPost() / doGet() 方法可以直接复制使用,按需传入对应参数即可。

一. Post发送方式

1. 封装请求参数:

{

"key ":" 123",

"appId":"0a42b68f-edca-489a-b2b8",

"pch":"88",

}

 将json数据封装成sendMap对象

Map<String, Object> sendMap = new HashMap<>();
sendMap.put("key", "123");
sendMap.put("appId","0a42b68f-edca-489a-b2b8");
sendMap.put("pch","88");
2. 填写发送路径:

sendUrl: http://127.0.0.1:8080/send/sendApp

3.将sendMap,sendUrl 传入到 doPost() 方法中 
 /**
     * 发送post请求
     * @param sendUrl 发送路径
     * @param sendMap 发送参数
     * @return StringBuilder 
     */
    public StringBuilder doPost(String sendUrl,Map<String, Object> sendMap){
        StringBuilder response = new StringBuilder();
        try {
            URL url = new URL(sendUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            JSONObject jsonObject = new JSONObject(sendMap);
            String s1 = jsonObject.toString();
            byte[] bytes = s1.getBytes();
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.write(bytes);
            wr.close();
            int statusCode = connection.getResponseCode();
            InputStream inputStream = statusCode == 200 ? connection.getInputStream() : connection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            inputStream.close();
            connection.disconnect();

        } catch (Exception e) {
            log.error("发送post请求异常:",e);
            e.printStackTrace();
        }
        return response;
    }
4. 解析stringBulider返回值

(a. json格式返回值方式 )

返回值以json形式举例 : {"code":"200","data":"123"},转成JSONObject方式,方便用key-value形式获取

JSONObject resultObject = JSONObject.parseObject(stringBulider.toString());

resultObject.get("code");

resultObject.get("data");

(b. 直接返回状态码方式:比如200)

String code = stringBulider.toString 即可。

二. Get发送方式

1.将所有参数封装在sendUrl路径上

sendUrl : http://127.0.0.1:8080/send/sendApp?username=aa&password=bb&id=abc

2. 将sendUrl参数传入doGet() 方法
 /**
     * 发送post请求
     * @param sendUrl 发送路径
     * @return stringBuffer 
     */
    public StringBuffer doGet(String sendUrl){
        StringBuffer stringBuffer = new StringBuffer();
        try{
            URL url = new URL(sendUrl);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            huc.setRequestProperty("Accept", "*/*");
            huc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            huc.setRequestProperty("Content-Language", "en-US");
            huc.setRequestProperty("Accept-Language","zh-CN");
            huc.setRequestProperty("Content-type","text/html");
            huc.connect();
            InputStreamReader  ir  = new InputStreamReader(huc.getInputStream());
            BufferedReader  br = new BufferedReader(ir) ;
            String line;
            while ((line = br.readLine()) != null) {
                stringBuffer.append(line);
            }
           br.close();
           ir.close();
           huc.disconnect();

        } catch (Exception e) {
            log.error("发送Get请求异常:",e);
            e.printStackTrace();
        }
        return stringBuffer;
    }
3. 解析stringBuffer返回值

(a. json格式返回值方式 )

返回值以json形式举例 : {"code":"200","data":"123"},转成JSONObject方式,方便用key-value形式获取

JSONObject resultObject = JSONObject.parseObject(stringBuffer.toString());

resultObject.get("code");

resultObject.get("data");

(b. 直接返回状态码方式:比如200)

String code = stringBulider.toString 即可。

  • 23
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序艺术

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值