Java HttpURLConnection发送post请求示例

public static Map<String, Object> invokeCapp(String urlStr, Map<String, Object> params) throws Exception {
    Map map = new HashMap();

    // post参数
    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) {
            postData.append('&');
        }
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    logger.info(postData.toString());
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    //开始访问
    HttpURLConnection conn = (HttpURLConnection)(new URL(urlStr)).openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setConnectTimeout(2000);
    conn.setReadTimeout(5000);
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;) {
        sb.append((char)c);
    }
    in.close();
    conn.disconnect();
    
    String responseStr = sb.toString();
    logger.info("RequestUtils - responseStr <== " + responseStr);
    if (StringHelper.isEmpty(responseStr)) {
        responseStr = "{}";
    }
    int statusCode = conn.getResponseCode();
    logger.info("RequestUtils - statusCode <== " + statusCode);
    if (HttpServletResponse.SC_OK == statusCode) {
        JSONObject dataJson = (JSONObject) JSONObject.parse(responseStr);
        map = new HashMap(dataJson);
    }
    
    return map;
}

 

posted @ 2019-01-29 11:30  carlo-z  阅读(10897)  评论(0编辑  收藏  举报