Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:net.daporkchop.porkbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p/>//from   w  w  w . j a  v a 2s. c o  m
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url         URL to submit the POST request to
 * @param post        POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequest(@NonNull URL url, @NonNull String post, @NonNull String contentType)
        throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return sendRequest(connection);
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userLocationProperties(DispatchContext ctx,
        Map<String, ? extends Object> context) throws IOException {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    String visitId = (String) context.get("visitId");

    if (Debug.infoOn()) {
        Debug.logInfo("In userLocationProperties", module);
    }/* ww w . j a v  a  2 s . c  o  m*/

    // get user coords
    coordsOfUserPosition(ctx, context);

    URL url = new URL(
            "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token="
                    + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Facebook stream = ", theString);

    if (theString.contains("AuthException") == true) {
        url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id=   283576871735609&"
                + "client_secret=   5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&"
                + "fb_exchange_token="
                + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");

        HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();

        // Set properties of the connection
        urlConnection1.setRequestMethod("GET");
        urlConnection1.setDoInput(true);
        urlConnection1.setDoOutput(true);
        urlConnection1.setUseCaches(false);
        urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Retrieve the output
        int responseCode1 = urlConnection1.getResponseCode();
        InputStream inputStream1;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream1 = urlConnection1.getInputStream();
        } else {
            inputStream1 = urlConnection1.getErrorStream();
        }

        StringWriter writer1 = new StringWriter();
        IOUtils.copy(inputStream1, writer1, "UTF-8");
        String theString1 = writer1.toString();

        Debug.logInfo("Facebook stream1 = ", theString1);

    }

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("geoName", "aaa");
    paramOut.put("abbreviation", "bbb");
    return paramOut;

}

From source file:com.gson.util.HttpKit.java

/**
 * /*from  ww  w .  j  a  v  a 2  s. c om*/
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?  
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??  
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); //  
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?  
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException {

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-type", "application/json");
    con.setRequestProperty("Accept", "application/json");

    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);/*from ww w.  j  a v  a2  s. co  m*/
    wr.flush();
    wr.close();

    logger.log(Level.INFO, "Sending POST request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();

}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {//from  ww w .j  a  va  2  s  .  c  o m
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * send a HTTP POST request/*  www  .jav a  2  s  .  c  o m*/
 * @param param
 * @param input_url
 * @return
 */
public static String POST(String param, String input_url) {
    try {
        URL url = new URL(input_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/xml");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        PrintWriter xmlOut = new PrintWriter(con.getOutputStream());
        xmlOut.write(param);
        xmlOut.flush();
        BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = "";
        String line;
        while ((line = response.readLine()) != null) {
            result += "\n" + line;
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * //ww w .  j  a v  a  2 s  .  c  om
 * 
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); // 
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);//from   w w  w.jav  a  2 s  .c  o  m
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}

From source file:com.memetix.gun4j.GunshortenAPI.java

protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception {
    final URL url = new URL(serviceUrl);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);

    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    final PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.write(paramsString);/*from  w  ww .j  ava2 s.  c o m*/
    pw.close();
    uc.getOutputStream().close();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Gunshorten API: " + result);
        }
        return parseJSON(result);
    } finally {
        uc.getInputStream().close();
        if (uc.getErrorStream() != null) {
            uc.getErrorStream().close();
        }
    }
}

From source file:net.cbtltd.server.WebService.java

/**
 * Gets the connection to the JSON server.
 *
 * @param url the connection URL.//  www .  ja  v a 2s .  c o  m
 * @param rq the request object.
 * @return the JSON string returned by the message.
 * @throws Throwable the exception thrown by the method.
 */
private static final String getConnection(URL url, String rq) throws Throwable {
    String jsonString = "";
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");

        if (rq != null) {
            connection.setRequestProperty("Accept", "application/json");
            connection.connect();
            byte[] outputBytes = rq.getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
        }

        if (connection.getResponseCode() != 200) {
            throw new RuntimeException("HTTP:" + connection.getResponseCode() + "URL " + url);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString += line;
        }
    } catch (Throwable x) {
        throw new RuntimeException(x.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return jsonString;
}