前面介绍了Java原生无依赖使用HttpURLConnection实现Get的例子,有时候需要是POST,所以给出POST的例子(内容Payload是JSON String)
/** * * @param url 请求地址 * @param headers 请求头,多个用key,value的形式存储,key为header的名称,value为header的值,可以为null * @param json 请求体,json格式的字符串 * @return 服务器返回值 */ public static String httpPostJson(String url, HashMap<String, String> headers, String json) throws IOException { HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); byte[] input = json.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); int responseCode = connection.getResponseCode(); if (responseCode != 200) { throw new IOException("http post error return code: " + responseCode + ", url: " + url); } BufferedReader br = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()).append("\n"); } return response.toString(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (connection != null) { connection.disconnect(); } } }
如果要发送form,那么只要Content-Type设置为:application/x-www-form-urlencoded
文章评论