Example usage for java.net HttpURLConnection setRequestMethod

List of usage examples for java.net HttpURLConnection setRequestMethod

Introduction

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

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

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);//  w  w w.j  av  a  2  s.c  o  m
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(param);
    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.java

private static void downloadResource(String from, String to) {
    OutputStream outputStream = null;
    BufferedInputStream inputStream = null;
    HttpURLConnection connection = null;
    URL url;/*from ww  w .  j  av  a 2  s  . c o m*/
    byte[] buffer = new byte[1024];

    try {
        url = new URL(from);

        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();
        outputStream = new FileOutputStream(to);

        inputStream = new BufferedInputStream(url.openStream());
        int read;

        while ((read = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, read);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (IOException e) {
            }
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        if (connection != null)
            connection.disconnect();
    }
}

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

public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody,
        boolean isEncodingNeeded) throws IOException {
    String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )";
    System.out.println(fqcn + " :: " + mn);
    URL restURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", userAgent);
    if (isEncodingNeeded)
        //conn.setRequestProperty("Content-Type", contentTypeURLENCODED);
        conn.setRequestProperty("Content-Type", contentTypeJSON);
    else//  w  w  w.jav a 2 s .  c om
        conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");

    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(requestBody);
    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:com.google.api.GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * /*from  w  w w.j  av a 2  s.c o  m*/
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.flush();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            pw.close();
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:lapispaste.Main.java

private static void paster(Map<String, String> pastemap, StringBuffer pdata) {
    try {//  ww  w .  ja v a 2s.c  om
        URL url = new URL("http://paste.linux-sevenler.org/index.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // set connection 'writeable'
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // construct the data...
        String data;
        String pdataString = pdata.toString();
        data = URLEncoder.encode("language", "ISO-8859-9") + "="
                + URLEncoder.encode(pastemap.get("format"), "ISO-8859-9");
        data += "&" + URLEncoder.encode("source", "ISO-8859-9") + "="
                + URLEncoder.encode(pdataString, "ISO-8859-9");
        data += "&" + URLEncoder.encode("submit", "ISO-8859-9") + "="
                + URLEncoder.encode(" Kaydet ", "ISO-8859-9");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // get new url where the paste is
        conn.getInputStream();
        System.out.println(conn.getURL());
        conn.disconnect();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java

private static String sendSingleEdit(String meetingID, String payload) throws IOException {
    String _url = getBaseUri().appendPath(meetingID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(IRequest.PUT);
    addRequestHeader(conn, false);//w  w  w .  j  a  v  a2s.  com
    sendPostPayload(conn, payload);
    return getServerResponse(conn);

}

From source file:com.meetingninja.csse.database.AgendaDatabaseAdapter.java

public static Agenda getAgenda(String agendaID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(agendaID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/* w  w w.  j a  v  a  2s. c o m*/

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    JsonNode agendaNode = MAPPER.readTree(response);

    return parseAgenda(agendaNode);
}

From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java

public static List<Contact> getContacts(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // add request header

    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);/*  www.j  av a2 s.  c  om*/
    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    List<Contact> contacts = new ArrayList<Contact>();
    List<String> contactIds = new ArrayList<String>();
    List<String> relationIds = new ArrayList<String>();
    final JsonNode contactsArray = MAPPER.readTree(response).get(Keys.User.CONTACTS);
    if (contactsArray.isArray()) {
        for (final JsonNode userNode : contactsArray) {
            relationIds.add(userNode.get(Keys.User.RELATIONID).asText());
            contactIds.add(userNode.get(Keys.User.CONTACTID).asText());
        }
    }

    conn.disconnect();
    for (int i = 0; i < contactIds.size(); i++) {

        User contact = UserDatabaseAdapter.getUserInfo(contactIds.get(i));
        if (contact != null) {
            Contact oneContact = new Contact(contact, relationIds.get(i));
            contacts.add(oneContact);
        }
    }
    return contacts;
}

From source file:core.RESTCalls.RESTPost.java

public static String httpPost(String urlStr, String[] paramName, String[] paramVal) throws Exception {

    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);//  ww w . j av  a2s  . c o m
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream out = conn.getOutputStream();

    Writer writer = new OutputStreamWriter(out, "UTF-8");

    for (int i = 0; i < paramName.length; i++) {

        writer.write(paramName[i]);
        writer.write("=");
        writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
        writer.write("&");
    }

    writer.close();
    out.close();

    if (conn.getResponseCode() != 200)
        throw new IOException(conn.getResponseMessage());

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    StringBuilder sb = new StringBuilder();

    String line;

    while ((line = rd.readLine()) != null)
        sb.append(line + "\n");

    rd.close();

    conn.disconnect();

    return sb.toString();
}

From source file:com.meetingninja.csse.database.GroupDatabaseAdapter.java

public static Group getGroup(String groupID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath(groupID).build().toString();

    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod("GET");
    addRequestHeader(conn, false);//from w ww  . ja v a 2  s  .  c  o  m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    JsonNode groupNode = MAPPER.readTree(response);

    return parseGroup(groupNode, new Group());
}