JAVA发送HTTP请求附带JSON数据与用户认证

本文介绍了如何使用Python通过Apache HttpClient发送POST请求,包括设置请求头、进行基本认证,并处理响应内容。示例中展示了如何构造参数和执行HTTP请求,适用于前后端交互的场景。

发送POST请求函数样例:

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

public String sendPost(String requestUrl, String param)  {
        InputStream inputStream = null;
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(requestUrl);
            // 设置请求头  Content-Type
            postMethod.setRequestHeader("Content-Type", "application/json");
            //Base64加密方式认证方式下的basic auth 
            postMethod.setRequestHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString(("username:password").getBytes()));
            RequestEntity requestEntity = new StringRequestEntity(param,"application/json","UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream =  postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br = null;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            System.out.print("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e){
            System.out.print("请求异常" +e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            if(inputStream != null) {
                try{
                    inputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

测试调用

import com.alibaba.fastjson.JSON;

Map<String, Object> prarms = new HashMap<>();
prarms.put("key", value);
String jsonPrarms = JSON.toJSONString(prarms);
mailEntity.sendPost("http://10.10.10.10:8000/mail", jsonPrarms);

邮箱中的换行符是<br/> 区别于代码中的换行符\n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值