java POST請求body傳參
阿新 • • 發佈:2019-01-06
public String post(String actionUrl, Map<String, String> params) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--"; String LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl);HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(30 * 1000); // 快取的最長時間 conn.setDoInput(true);// 允許輸入 conn.setDoOutput(true);// 允許輸出 conn.setUseCaches(false); // 不允許使用快取 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); StringBuilder sb = new StringBuilder(); if (params!=null) { // 首先組拼文字型別的引數 for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY);sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); if (!TextUtils.isEmpty(sb.toString())) { outStream.write(sb.toString().getBytes()); } // 請求結束標誌 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到響應碼 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); if (res == 200) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = bufferedReader.readLine()) != null){ buffer.append(line); } // int ch; // StringBuilder sb2 = new StringBuilder(); // while ((ch = in.read()) != -1) { // sb2.append((char) ch); // } return buffer.toString(); } outStream.close(); conn.disconnect(); return in.toString(); }