Java - sending HTTP parameters via POST method easily

前端 未结 17 1757
借酒劲吻你
借酒劲吻你 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:49

    Here is a simple example that submits a form then dumps the result page to System.out. Change the URL and the POST params as appropriate, of course:

    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    class Test {
        public static void main(String[] args) throws Exception {
            URL url = new URL("http://example.net/new-message.php");
            Map params = new LinkedHashMap<>();
            params.put("name", "Freddie the Fish");
            params.put("email", "fishie@seamail.example.com");
            params.put("reply_to_thread", 10394);
            params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish.");
    
            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"));
            }
            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"));
    
            for (int c; (c = in.read()) >= 0;)
                System.out.print((char)c);
        }
    }
    

    If you want the result as a String instead of directly printed out do:

            StringBuilder sb = new StringBuilder();
            for (int c; (c = in.read()) >= 0;)
                sb.append((char)c);
            String response = sb.toString();
    

提交回复
热议问题