Java send http request code example

/**
 * Created by shangyidong on 16/7/28.
 */
public class HttpUtil {
    private static final AvatarLogger logger = AvatarLoggerFactory.getLogger(HttpUtil.class);

    /**
     * Send a GET method request to the specified URL
     *
     * @param url
     * The URL to send the request to
     * @param param
     * Request parameter, the request parameter should be in the form of name1=value1&name2=value2.
     * The response result of the remote resource represented by the @return URL
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // open the connection to the URL
            URLConnection connection = realUrl.openConnection();
            // Set common request attributes
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // establish the actual connection
            connection.connect();
            /*
            // Get all response header fields
            Map<String, List<String>> map = connection.getHeaderFields();
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            */
            // loop through all response header fields
            // Define the BufferedReader input stream to read the response from the URL
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("Error sending GET request", e);
        } finally {//Close the input stream
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
        return result;
    }

    /**
     * Send a POST request to the specified URL
     *
     * @param url
     * The URL to send the request to
     * @param param
     * Request parameter, the request parameter should be in the form of name1=value1&name2=value2.
     * The response result of the remote resource represented by @return
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL (url);
            // open the connection to the URL
            URLConnection conn = realUrl.openConnection();
            // Set common request attributes
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // Sending a POST request must set the following two lines
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // Get the output stream corresponding to the URLConnection object
            out = new PrintWriter(conn.getOutputStream());
            // send request parameters
            out.print(param);
            // flush the buffer of the output stream
            out.flush();
            // Define the BufferedReader input stream to read the response from the URL
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("Error sending POST request", e);
        } finally {
            //Close the output stream, input stream
            try {
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            } catch (IOException e){
                logger.error(e);
            }
        }
        return result;
    }

    public static String sendPostMethod(String url, String title, String content, String warnContactList){
        return sendPost(url, "domain=&typeItem=Page&level=1&url=&title=" + title + "&typeObject=Web&content=" + content + "&source=mkt-monitor&typeAttribute=Content¬ifier=[" + warnContactList + "]&severity=high");
    }

    public static void main(String[] args){
        //Send GET request
        //String s = HttpUtil.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
        //System.out.println(s);

        // send POST request
        String sr = HttpUtil.sendPost("http://****/report/alarm", "domain=&typeItem=Page&level=1&url=&title=测试告警测试告警test&typeObject=Web&content=测试告警内容&source=mkt-monitor&typeAttribute=Content¬ifier=[{\"mobile\": \"170****0278\", \"notify_methods\": \"email,weixin,sms\", \"email\": \"shangyidong@***.com\", \"name\": \"shangyidong\"},{\"mobile\": \"183****6723\", \"notify_methods\": \"email,weixin,sms\", \"email\": \"yangcheng15@***.com\", \"name\": \"yangcheng15\"}]&severity=high");
        System.out.println(sr);
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326231560&siteId=291194637