Java HTTP Post post(String url, String payload)

Here you can find the source of post(String url, String payload)

Description

post

License

Open Source License

Declaration

public static String post(String url, String payload) throws IOException 

Method Source Code

//package com.java2s;
/**/*from  w  ww  . j  a  v a 2s  . co  m*/
 * Copyright (c) 2010-2016 by the respective copyright holders.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    private static final String USER_AGENT = "Java";

    public static String post(String url, String payload) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(payload);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        if (responseCode != 200) {
            throw new IOException("Response Code: " + responseCode);
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        try {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } finally {
            in.close();
        }
    }
}

Related

  1. post(String rawUrl, String body)
  2. post(String url, int timeout, Map header)
  3. post(String url, JsonNode body)
  4. post(String url, Map params, String charset)
  5. post(String url, String body, Map headers)
  6. post(String url, String postdata, String cookie)
  7. Post(URL url, Map fields)
  8. post(URL url, Map values)
  9. post(URL url, String content)