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 (responseStr.isEmpty()) {
        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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可能是因为你在使用 HttpURLConnection 发送 post 请求时没有正确设置请求头和请求参数。以下是一个简单的示例代码,你可以参考一下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionPostExample { private static final String POST_URL = "http://example.com/api/post"; public static void main(String[] args) throws IOException { URL url = new URL(POST_URL); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setDoOutput(true); String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; OutputStream os = con.getOutputStream(); os.write(requestBody.getBytes()); os.flush(); os.close(); int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } } ``` 在上述代码中,我们首先创建了一个 `URL` 对象,表示要发送 post 请求的地址。然后我们使用 `HttpURLConnection` 类的 `openConnection()` 方法打开连接,并设置请求方法为 POST,设置请求头为 `Content-Type: application/json`,并将 `doOutput` 属性设置为 `true`,以便我们可以向服务器发送请求体。 接下来,我们将请求体写入输出流,并调用 `flush()` 和 `close()` 方法将其发送到服务器。然后我们使用 `getResponseCode()` 方法获取服务器响应的状态码,并使用 `getInputStream()` 方法获取服务器响应的输入流。最后,我们从输入流读取响应体,并将其转换为字符串。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值