Java HTTP Post httpPost(String httpUrl)

Here you can find the source of httpPost(String httpUrl)

Description

http Post

License

Apache License

Declaration

public static String httpPost(String httpUrl) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

public class Main {
    public static String httpPost(String httpUrl) {
        BufferedReader input = null;
        StringBuilder sb = null;/*  w ww . j  a v a2s  . c o  m*/
        URL url = null;
        HttpURLConnection con = null;
        try {
            url = new URL(httpUrl);
            try {
                con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                input = new BufferedReader(new InputStreamReader(con.getInputStream()));
                sb = new StringBuilder();
                String s;
                while ((s = input.readLine()) != null) {
                    sb.append(s).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } finally {
            // close buffered
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // disconnecting releases the resources held by a connection so they may be closed or reused
            if (con != null) {
                con.disconnect();
            }
        }

        return sb == null ? null : sb.toString();
    }

    public static String httpPost(String httpUrl, Map<String, String> params) {
        return httpPost(httpUrl + map2url(params));
    }

    private static String map2url(Map<String, String> params) {
        String str = "?";
        for (Map.Entry<String, String> entry : params.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            str += entry.getKey() + "=" + entry.getValue() + "&";
        }
        return str;
    }
}

Related

  1. executePost(String url, JSONObject data)
  2. executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
  3. getHttpPOSTConnection(String urlStr, String charSet, Map props, Map params)
  4. httpGet(final String httpurl, final Map... requestProperties)
  5. httpPost(final String httpurl, final String data, final Map... requestProperties)
  6. httpPost(String url, StringBuffer data)
  7. httpPost(String urlToRead, String post)
  8. httpPostText(String urlStr, String textString)
  9. post(String json, String url)