Java - sending HTTP parameters via POST method easily

前端 未结 17 1732
借酒劲吻你
借酒劲吻你 2020-11-21 05:54

I am successfully using this code to send HTTP requests with some parameters via GET method

void sendRequest(String request)
{
            


        
17条回答
  •  温柔的废话
    2020-11-21 06:32

    I had the same issue. I wanted to send data via POST. I used the following code:

        URL url = new URL("http://example.com/getval.php");
        Map params = new LinkedHashMap<>();
        params.put("param1", param1);
        params.put("param2", param2);
    
        StringBuilder postData = new StringBuilder();
        for (Map.Entry 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"));
        }
        String urlParameters = postData.toString();
        URLConnection conn = url.openConnection();
    
        conn.setDoOutput(true);
    
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    
        writer.write(urlParameters);
        writer.flush();
    
        String result = "";
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
        while ((line = reader.readLine()) != null) {
            result += line;
        }
        writer.close();
        reader.close()
        System.out.println(result);
    

    I used Jsoup for parse:

        Document doc = Jsoup.parseBodyFragment(value);
        Iterator opts = doc.select("option").iterator();
        for (;opts.hasNext();) {
            Element item = opts.next();
            if (item.hasAttr("value")) {
                System.out.println(item.attr("value"));
            }
        }
    

提交回复
热议问题