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; } }
HttpConnection底层代码实现Post方法
最新推荐文章于 2023-06-22 17:31:51 发布