HttpConnection底层代码实现Post方法

public class HttpConnectionPost {

    public HttpConnectionPost() {
    }
//
    public static byte[] doPostRequest(String path, Map<String, Object> map, String encode) throws MalformedURLException {
        StringBuffer stringBuffer = new StringBuffer();
        URL url = new URL(path);
        try {
            if (map != null && !map.isEmpty()) {
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String key = entry.getKey();
                    String value = (String) entry.getValue();
                    String EncoderValue = URLEncoder.encode(value, encode);
                    stringBuffer.append(key).append("=").append(EncoderValue).append("&");
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//以上部分为构建一个StringBuffer字符串变量,动态添加Map数据封装在对象中,在下一部分代码块被调用分解成字节数组传入流中
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = null;
            connection.setConnectTimeout(3000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            byte[] indata = stringBuffer.toString().getBytes();
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", String.valueOf(indata.length));
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(indata);
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                inputStream = connection.getInputStream();
            }
前半部分代码块实现将Map数据封装并传入服务器端,在取得服务器响应后,得到一个输入流到客户端,再调用输出流写出服务器响应的信息
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] outdata = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(outdata)) != -1) {
                byteArrayOutputStream.write(outdata, 0, len);
            }
            byte[] mdata = byteArrayOutputStream.toByteArray();
            return mdata;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
/
    public static String getString(byte[] data) {
        String result = null;
        try {
            result = new String(data,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值