Java发送Post请求

Posted 水木仕林

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java发送Post请求相关的知识,希望对你有一定的参考价值。

      //访问准备 
      URL url = new URL("http:***");
      //post参数
       Map<String,Object> params = new LinkedHashMap<>();
            params.put("geomInfo", "");
            params.put("f", "json");

       //开始访问
        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"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        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);
        String response = sb.toString();
        System.out.println(response);
        return response;        

  

以上是关于Java发送Post请求的主要内容,如果未能解决你的问题,请参考以下文章

怎么用javascript发送post请求?

求教golang中http发送post请求gb2312编码的解决方案

java接受post请求问题,求大侠帮忙~~

用java做一个httpClient 发送https 的get请求,需要证书验证的那种,求大神指点一下!

java中如何判断发送的请求是不是得到响应

java使用POST发送soap报文请求webservice返回500错误解析