Example usage for javax.net.ssl HttpsURLConnection setRequestMethod

List of usage examples for javax.net.ssl HttpsURLConnection setRequestMethod

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);//from   ww w .  j av  a  2s  .c  o  m
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:edu.hackathon.perseus.core.httpSpeedTest.java

public void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

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

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);/*from w  w w .  ja  v  a2s .  c o  m*/
    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);
    }
    in.close();

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

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void putGetFileExample() throws Exception {
    HttpsURLConnection connection;
    String redirect;//from w  w  w.j  av  a  2  s  .  c  om
    InputStream input;
    OutputStream output;

    String data = UUID.randomUUID().toString();

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=CREATE");
    connection.setRequestMethod("PUT");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    output = connection.getOutputStream();
    IOUtils.write(data.getBytes(), output);
    output.close();
    connection.disconnect();
    assertThat(connection.getResponseCode(), is(201));

    connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=OPEN");
    assertThat(connection.getResponseCode(), is(307));
    redirect = connection.getHeaderField("Location");
    connection.disconnect();

    connection = createHttpUrlConnection(redirect);
    input = connection.getInputStream();
    assertThat(IOUtils.toString(input), is(data));
    input.close();
    connection.disconnect();

}

From source file:org.jboss.aerogear.adm.TokenService.java

/**
 * Returns HttpsURLConnection that 'posts' the given payload to ADM.
 *//*from w  w  w .ja  v  a2s  .c o  m*/
private HttpsURLConnection post(final String payload) throws Exception {

    final HttpsURLConnection conn = getHttpsURLConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);

    // Set the content type .
    conn.setRequestProperty("content-type", APPLICATION_X_WWW_FORM_URLENCODED);
    conn.setRequestProperty("charset", UTF_8);

    conn.setRequestMethod("POST");

    OutputStream out = null;
    final byte[] bytes = payload.getBytes(UTF_8_CHARSET);
    try {
        out = conn.getOutputStream();
        out.write(bytes);
        out.flush();
    } finally {
        // in case something blows up, while writing
        // the payload, we wanna close the stream:
        if (out != null) {
            out.close();
        }
    }

    return conn;
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * //from   w w w. java 2  s.  com
 * @param con ?HttpsURLConnection 
 * @return con option??HttpsURLConnection
 */
protected HttpsURLConnection setHttpHeader(HttpsURLConnection con) {
    try {
        con.setRequestMethod(this.method);
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("Accept-Language", this.lang);
        con.setRequestProperty("Accept", this.accept);
        con.setRequestProperty("appid", this.appid);
        System.out.println("Accept: " + con.getRequestProperty("Accept"));
        System.out.println("appid: " + con.getRequestProperty("appid"));
        return con;
    } catch (ProtocolException e) {
        e.printStackTrace();
        return con;
    }
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {//  w  w  w . ja  va2s .com
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?//from www  . java 2s .  c om
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {/* ww  w .java 2  s.  c  o m*/
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request//from  w w w. ja  v  a  2  s.  co  m
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:pack_test.Get_stream.java

/**
 * Run the web service request/*w w w  . j  av a  2s. com*/
 */
//public static void main(String[] args) {
public void main() {
    HttpsURLConnection conn = null;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL(
                "https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
    } catch (Exception e) {
        // Print any exceptions that occur
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}