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:yodlee.ysl.api.io.HTTP.java

public static String doPost(String url, String requestBody) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(requestBody);//from w  w  w  . j  a  v a2s .  co  m
    wr.flush();
    wr.close();
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request");
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

private static HttpURLConnection openHTTPConnection(String urlString, HttpVerbs verb)
        throws MalformedURLException, IOException {
    URL url = null;/* w ww  .ja v  a 2 s  .  c om*/
    HttpURLConnection conn = null;

    url = new URL(urlString);
    conn = (HttpURLConnection) url.openConnection();

    switch (verb) {
    case POST:
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        break;
    case PUT:
        conn.setRequestMethod("PUT");
        conn.setDoOutput(true);
        break;
    case DELETE:
        conn.setRequestMethod("DELETE");
        break;
    default:
        conn.setRequestMethod("GET");
        break;
    }

    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Content-type", "application/json");

    return conn;
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        VolleyLog.e("======3:" + request.getBodyContentType());
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);//from   w  w w . ja v a2  s.  c om
        out.close();
    }
}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Creates a CouchDB view/* www . ja v a2s .co m*/
 */
public static void makeView(String user, String pw, String url, String viewDef) throws SQLException {
    try {
        URL u = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setRequestMethod("PUT");
        OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
        wr.write(viewDef);
        wr.close();

        String s = readStringFromConnection(uc);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(e.getMessage());
    }
}

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

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p/>//w w  w .  j a va  2s .co 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 performPostRequestWithAuth(@NonNull URL url, @NonNull String post,
        @NonNull String contentType, @NonNull String auth) throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    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:yodlee.ysl.api.io.HTTP.java

public static String doPutNew(String url, String param, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(PUT :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    //param=param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C").replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+");
    String processedURL = url;//+"?MFAChallenge="+param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D";
    URL myURL = new URL(processedURL);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Content-Type", contentTypeJSON);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(param);/*  w ww. j a v  a2  s.  c om*/
    wr.flush();
    wr.close();
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:Main.IrcBot.java

public static void postRequest(String pasteCode, PrintWriter out) {
    try {//from w w  w .  jav a  2  s.c  om
        String url = "http://pastebin.com/raw.php?i=" + pasteCode;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\n");
        }
        in.close();

        //print result
        System.out.println(response.toString());

        if (response.length() > 0) {
            IrcBot.postGit(response.toString(), out);
        } else {
            out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid.");
        }
    } catch (Exception p) {

    }
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doPut(String url, String param, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(PUT :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    param = param.replace("\"", "%22").replace("{", "%7B").replace("}", "%7D").replace(",", "%2C")
            .replace("[", "%5B").replace("]", "%5D").replace(":", "%3A").replace(" ", "+");
    String processedURL = url + "?MFAChallenge=" + param;//"%7B%22loginForm%22%3A%7B%22formType%22%3A%22token%22%2C%22mfaTimeout%22%3A%2299380%22%2C%22row%22%3A%5B%7B%22id%22%3A%22token_row%22%2C%22label%22%3A%22Security+Key%22%2C%22form%22%3A%220001%22%2C%22fieldRowChoice%22%3A%220001%22%2C%22field%22%3A%5B%7B%22id%22%3A%22token%22%2C%22name%22%3A%22tokenValue%22%2C%22type%22%3A%22text%22%2C%22value%22%3A%22123456%22%2C%22isOptional%22%3Afalse%2C%22valueEditable%22%3Atrue%2C%22maxLength%22%3A%2210%22%7D%5D%7D%5D%7D%7D";
    URL myURL = new URL(processedURL);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + processedURL.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Accept-Charset", "UTF-8");
    conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP PUT' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;/*from  w w  w  . j  ava 2s . c  o m*/
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException {
    HttpResponse httpResponse;/* w  w  w.  j a v a2s  . c  o  m*/
    if (endpoint.startsWith("http://")) {
        URL url = new URL(endpoint);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        conn.setReadTimeout(30000);

        // setting headers
        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                conn.setRequestProperty(key, headers.get(key));
            }
        }

        conn.connect();

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());

        } catch (IOException ignored) {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode());
            httpResponse.setResponseMessage(conn.getResponseMessage());
        } finally {
            if (rd != null) {
                rd.close();
            }
        }

        return httpResponse;
    }
    return null;
}

From source file:com.sungtech.goodTeacher.action.TeacherInfoAction.java

public static String httpUrlRequest(String requestURL, String json) {
    URL url;//from  w ww .j a  va 2 s.  c o m
    String response = "";
    HttpURLConnection connection = null;
    InputStream is = null;
    try {
        url = new URL(requestURL);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.getOutputStream().write(json.getBytes());
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        int code = connection.getResponseCode();
        System.out.println("code" + code);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
    return response;
}