Java - sending HTTP parameters via POST method easily

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

    I couldn't get Alan's example to actually do the post, so I ended up with this:

    String urlParameters = "param1=a&param2=b&param3=c";
    URL url = new URL("http://example.com/index.php");
    URLConnection conn = url.openConnection();
    
    conn.setDoOutput(true);
    
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    
    writer.write(urlParameters);
    writer.flush();
    
    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    writer.close();
    reader.close();         
    
    0 讨论(0)
  • 2020-11-21 06:41

    I see some other answers have given the alternative, I personally think that intuitively you're doing the right thing ;). Sorry, at devoxx where several speakers have been ranting about this sort of thing.

    That's why I personally use Apache's HTTPClient/HttpCore libraries to do this sort of work, I find their API to be easier to use than Java's native HTTP support. YMMV of course!

    0 讨论(0)
  • 2020-11-21 06:43

    GET and POST method set like this... Two types for api calling 1)get() and 2) post() . get() method to get value from api json array to get value & post() method use in our data post in url and get response.

     public class HttpClientForExample {
    
        private final String USER_AGENT = "Mozilla/5.0";
    
        public static void main(String[] args) throws Exception {
    
            HttpClientExample http = new HttpClientExample();
    
            System.out.println("Testing 1 - Send Http GET request");
            http.sendGet();
    
            System.out.println("\nTesting 2 - Send Http POST request");
            http.sendPost();
    
        }
    
        // HTTP GET request
        private void sendGet() throws Exception {
    
            String url = "http://www.google.com/search?q=developer";
    
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
    
            // add request header
            request.addHeader("User-Agent", USER_AGENT);
    
            HttpResponse response = client.execute(request);
    
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + 
                           response.getStatusLine().getStatusCode());
    
            BufferedReader rd = new BufferedReader(
                           new InputStreamReader(response.getEntity().getContent()));
    
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
    
            System.out.println(result.toString());
    
        }
    
        // HTTP POST request
        private void sendPost() throws Exception {
    
            String url = "https://selfsolve.apple.com/wcResults.do";
    
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
    
            // add header
            post.setHeader("User-Agent", USER_AGENT);
    
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
            urlParameters.add(new BasicNameValuePair("cn", ""));
            urlParameters.add(new BasicNameValuePair("locale", ""));
            urlParameters.add(new BasicNameValuePair("caller", ""));
            urlParameters.add(new BasicNameValuePair("num", "12345"));
    
            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    
            HttpResponse response = client.execute(post);
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + post.getEntity());
            System.out.println("Response Code : " + 
                                        response.getStatusLine().getStatusCode());
    
            BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
    
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
    
            System.out.println(result.toString());
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 06:43

    here i sent jsonobject as parameter //jsonobject={"name":"lucifer","pass":"abc"}//serverUrl = "http://192.168.100.12/testing" //host=192.168.100.12

      public static String getJson(String serverUrl,String host,String jsonobject){
    
        StringBuilder sb = new StringBuilder();
    
        String http = serverUrl;
    
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(http);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setUseCaches(false);
            urlConnection.setConnectTimeout(50000);
            urlConnection.setReadTimeout(50000);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Host", host);
            urlConnection.connect();
            //You Can also Create JSONObject here 
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            out.write(jsonobject);// here i sent the parameter
            out.close();
            int HttpResult = urlConnection.getResponseCode();
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                Log.e("new Test", "" + sb.toString());
                return sb.toString();
            } else {
                Log.e(" ", "" + urlConnection.getResponseMessage());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-21 06:45

    I higly recomend http-request built on apache http api.

    For your case you can see example:

    private static final HttpRequest<String.class> HTTP_REQUEST = 
          HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
               .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
               .build();
    
    public void sendRequest(String request){
         String parameters = request.split("\\?")[1];
         ResponseHandler<String> responseHandler = 
                HTTP_REQUEST.executeWithQuery(parameters);
    
       System.out.println(responseHandler.getStatusCode());
       System.out.println(responseHandler.get()); //prints response body
    }
    

    If you are not interested in the response body

    private static final HttpRequest<?> HTTP_REQUEST = 
         HttpRequestBuilder.createPost("http://example.com/index.php").build();
    
    public void sendRequest(String request){
         ResponseHandler<String> responseHandler = 
               HTTP_REQUEST.executeWithQuery(parameters);
    }
    

    For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java

    0 讨论(0)
  • 2020-11-21 06:46

    Appears that you also have to callconnection.getOutputStream() "at least once" (as well as setDoOutput(true)) for it to treat it as a POST.

    So the minimum required code is:

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful
        connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call...
        connection.connect();
        connection.getOutputStream().close(); 
    

    You can even use "GET" style parameters in the urlString, surprisingly. Though that might confuse things.

    You can also use NameValuePair apparently.

    0 讨论(0)
提交回复
热议问题