开发者社区> 问答> 正文

java怎么发送post请求

java怎么发送post请求

展开
收起
云计算小粉 2018-05-10 20:07:14 4639 0
2 条回答
写回答
取消 提交回答
  • 在java中使用http的方式向远程服务器发送POST请求,代码:

    // HTTP POST请求
    private void sendPost() throws Exception {
    
        String url = "https://selfsolve.apple.com/wcResults.do";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    
        //添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    
        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
    
        //发送Post请求
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        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());
    }
    
    2019-07-17 22:15:04
    赞同 展开评论 打赏
  • 参考下URL ,HttpURLConnection ;
    2019-07-17 22:15:04
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载