HttpURLConnection URL BufferedReader InputStream 发送请求 解决字符编码问题

本文介绍了一个投保接口的具体实现过程,包括参数处理、签名生成、HTTP请求发送及响应处理等关键步骤,并展示了如何通过一系列编码技巧确保数据的安全传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RequestMapping(path = "/v1/ht", produces = {"application/json;charset=UTF-8"})

@PostMapping("/htInsuredSubmit")
public ResultDTO<Map<String, String>> htInsuredSubmit(@RequestBody String strAppInfo,HttpServletRequest request){
try {
LogHelper.commoninfo("==========API==strAppInfo===="+strAppInfo);
// 针对url传递特殊字符转译问题
strAppInfo = strAppInfo.replaceAll("%","%25");
LogHelper.commoninfo("==========API==strAppInfo===="+strAppInfo);
String signature = MD5Util.MD5Encode(strAppInfo + ENCRYPT_VAL, "utf-8"); // 加密
// 发送数据,获取响应
    String jsonStr = HttpClientConfig.requestService(htInsuredSubmitUrl, "json="+strAppInfo+"&channelCode="+CHANNELCODE+"&signature="+signature);
return new ResultDTO<>(ResultDTO.CODE_SUCCESS,jsonStr);
} catch (Exception e) {
LogHelper.commonerror("HrInsuredController.htInsuredSubmit:" + e.getMessage(), e);
return new ResultDTO<>(ResultDTO.CODE_DEFAULT_FAIL, "投保失败,请重试!");
}


public static String requestService(String toURL,String data) throws Exception {
StringBuffer bs = new StringBuffer();
URL url = new URL(toURL);
HttpURLConnection urlcon=null;
String proxyUrl="10.9.1.5";
int proxyProt=3128;
// 打开和URL之间的连接
            if(isProxy){
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(proxyUrl, proxyProt));
            urlcon = (HttpURLConnection) url.openConnection(proxy);
            }else{
            urlcon = (HttpURLConnection) url.openConnection();
            }  
urlcon.setRequestMethod("POST");
urlcon.setUseCaches(false);
urlcon.setConnectTimeout(30000);
urlcon.setReadTimeout(30000);
urlcon.setDoInput(true);
urlcon.setDoOutput(true);
urlcon.setRequestProperty("accept", "*/*");
urlcon.setRequestProperty("Accept-Charset", "UTF-8");
urlcon.setRequestProperty("contentType", "UTF-8");
urlcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = urlcon.getOutputStream();
out.write(data.getBytes("UTF-8"));
out.flush();
out.close();
urlcon.connect();
InputStream is = urlcon.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(is,"UTF-8"));
String l = null;
while ((l = buffer.readLine()) != null) {
bs.append(l);
}
return bs.toString();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值