JAVA HttpURLConnection请求

首先,贴一段请求的完整代码

public static String httpDomain(String urlStr, Map<String, String> params) {
        URL connect;
        OutputStreamWriter paramout = null;
        BufferedReader reader = null;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);// post不能使用缓存
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 转换请求所需参数格式
            String paramsStr = JSONObject.toJSONString(params);
            paramout = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
            paramout.write(paramsStr);
            paramout.flush();

            // 获取URLConnection对象对应的输入流
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
            is.close();
        } catch (Exception e) {
            String msg = "异常消息";
            log.error(msg, e);
        } finally {
            try {
                if (null != paramout) {
                    paramout.close();
                }
                if (null != reader) {
                    reader.close();
                }
            } catch (IOException e) {
                String msg = "流关闭错误";
                log.error(msg, e);
            }
        }
        return data.toString();
    }

需要特别注意的是,如果服务器需要的是JSON格式的参数,那无论客户端是什么类型的参数,都需要通过以下方式转换为JSON格式的字符串,要么调用时很可能返回400错误,切记!

// 转换请求所需参数格式
String paramsStr = JSONObject.toJSONString(params);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值