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.liberty.android.fantastischmemo.downloader.google.GoogleAccountActivity.java

@Override
protected String[] getAccessTokens(final String[] requests) throws IOException {
    String code = requests[0];//  w  ww.j  a v a 2 s  .  co m
    URL url1 = new URL("https://accounts.google.com/o/oauth2/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("code=%s&client_id=%s&client_secret=%s&redirect_uri=%s&grant_type=%s",
            URLEncoder.encode(code, "UTF-8"), URLEncoder.encode(AMEnv.GOOGLE_CLIENT_ID, "UTF-8"),
            URLEncoder.encode(AMEnv.GOOGLE_CLIENT_SECRET, "UTF-8"),
            URLEncoder.encode(AMEnv.GOOGLE_REDIRECT_URI, "UTF-8"),
            URLEncoder.encode("authorization_code", "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    String s = new String(IOUtils.toByteArray(conn.getInputStream()));
    try {
        JSONObject jsonObject = new JSONObject(s);
        String accessToken = jsonObject.getString("access_token");
        //String refreshToken= jsonObject.getString("refresh_token");
        return new String[] { accessToken };
    } catch (JSONException e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    }
}

From source file:org.sakaiproject.contentreview.turnitin.util.TurnitinAPIUtil.java

public static InputStream callTurnitinReturnInputStream(String apiURL, Map<String, Object> parameters,
        String secretKey, int timeout, Proxy proxy, boolean isMultipart)
        throws TransientSubmissionException, SubmissionException {
    InputStream togo = null;/*w  ww .  jav  a 2  s  .  c  o  m*/

    StringBuilder apiDebugSB = new StringBuilder();

    if (!parameters.containsKey("fid")) {
        throw new IllegalArgumentException("You must to include a fid in the parameters");
    }

    //if (!parameters.containsKey("gmttime")) {
    parameters.put("gmtime", getGMTime());
    //}

    /**
     * Some debug logging
     */
    if (log.isDebugEnabled()) {
        Set<Entry<String, Object>> ets = parameters.entrySet();
        Iterator<Entry<String, Object>> it = ets.iterator();
        while (it.hasNext()) {
            Entry<String, Object> entr = it.next();
            log.debug("Paramater entry: " + entr.getKey() + ": " + entr.getValue());
        }
    }

    List<String> sortedkeys = new ArrayList<String>();
    sortedkeys.addAll(parameters.keySet());

    String md5 = buildTurnitinMD5(parameters, secretKey, sortedkeys);

    HttpsURLConnection connection;
    String boundary = "";
    try {
        connection = fetchConnection(apiURL, timeout, proxy);
        connection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        if (isMultipart) {
            Random rand = new Random();
            //make up a boundary that should be unique
            boundary = Long.toString(rand.nextLong(), 26) + Long.toString(rand.nextLong(), 26)
                    + Long.toString(rand.nextLong(), 26);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        }

        log.debug("HTTPS Connection made to Turnitin");

        OutputStream outStream = connection.getOutputStream();

        if (isMultipart) {
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting Multipart TII CALL:\n");
            }
            for (int i = 0; i < sortedkeys.size(); i++) {
                if (parameters.get(sortedkeys.get(i)) instanceof ContentResource) {
                    ContentResource resource = (ContentResource) parameters.get(sortedkeys.get(i));
                    outStream.write(
                            ("--" + boundary + "\r\nContent-Disposition: form-data; name=\"pdata\"; filename=\""
                                    + resource.getId() + "\"\r\n" + "Content-Type: " + resource.getContentType()
                                    + "\r\ncontent-transfer-encoding: binary" + "\r\n\r\n").getBytes());
                    //TODO this loads the doc into memory rather use the stream method
                    byte[] content = resource.getContent();
                    if (content == null) {
                        throw new SubmissionException("zero length submission!");
                    }
                    outStream.write(content);
                    outStream.write("\r\n".getBytes("UTF-8"));
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ContentHostingResource: ");
                        apiDebugSB.append(resource.getId());
                        apiDebugSB.append("\n");
                    }
                } else {
                    if (apiTraceLog.isDebugEnabled()) {
                        apiDebugSB.append(sortedkeys.get(i));
                        apiDebugSB.append(" = ");
                        apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                        apiDebugSB.append("\n");
                    }
                    outStream.write(encodeParam(sortedkeys.get(i), parameters.get(sortedkeys.get(i)).toString(),
                            boundary).getBytes());
                }
            }
            outStream.write(encodeParam("md5", md5, boundary).getBytes());
            outStream.write(("--" + boundary + "--").getBytes());

            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiDebugSB.append("\n");
                apiTraceLog.debug(apiDebugSB.toString());
            }
        } else {
            writeBytesToOutputStream(outStream, sortedkeys.get(0), "=",
                    parameters.get(sortedkeys.get(0)).toString());
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("Starting TII CALL:\n");
                apiDebugSB.append(sortedkeys.get(0));
                apiDebugSB.append(" = ");
                apiDebugSB.append(parameters.get(sortedkeys.get(0)).toString());
                apiDebugSB.append("\n");
            }

            for (int i = 1; i < sortedkeys.size(); i++) {
                writeBytesToOutputStream(outStream, "&", sortedkeys.get(i), "=",
                        parameters.get(sortedkeys.get(i)).toString());
                if (apiTraceLog.isDebugEnabled()) {
                    apiDebugSB.append(sortedkeys.get(i));
                    apiDebugSB.append(" = ");
                    apiDebugSB.append(parameters.get(sortedkeys.get(i)).toString());
                    apiDebugSB.append("\n");
                }
            }

            writeBytesToOutputStream(outStream, "&md5=", md5);
            if (apiTraceLog.isDebugEnabled()) {
                apiDebugSB.append("md5 = ");
                apiDebugSB.append(md5);
                apiTraceLog.debug(apiDebugSB.toString());
            }
        }

        outStream.close();

        togo = connection.getInputStream();
    } catch (IOException t) {
        log.error("IOException making turnitin call.", t);
        throw new TransientSubmissionException("IOException making turnitin call.", t);
    } catch (ServerOverloadException t) {
        throw new TransientSubmissionException("Unable to submit the content data from ContentHosting", t);
    }

    return togo;

}

From source file:it.serverSystem.HttpsTest.java

private void connectUntrusted() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from  www.  j  a  v a  2 s  .  c om*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    // SSLv3 is disabled since SQ 4.5.2 : https://jira.codehaus.org/browse/SONAR-5860
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory untrustedSocketFactory = sc.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    URL url = new URL("https://localhost:" + httpsPort + "/sessions/login");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(true);
    connection.setSSLSocketFactory(untrustedSocketFactory);
    connection.setHostnameVerifier(allHostsValid);

    InputStream input = connection.getInputStream();
    checkCookieFlags(connection);
    try {
        String html = IOUtils.toString(input);
        assertThat(html).contains("<body");
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.aankor.animenforadio.api.WebsiteGate.java

private void fetchCookies() throws IOException {
    if (phpSessID.equals("")) {
        URL url = new URL("https://www.animenfo.com/radio/index.php");
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.connect();//from  ww w  .  j a  v  a 2 s .c  o  m
        updateCookies(con);
    }
}

From source file:com.example.onenoteservicecreatepageexample.SendRefreshTokenAsyncTask.java

private Object[] attemptRefreshAccessToken(String refreshToken) throws Exception {
    /**//w w w . ja  va2s .  co m
     * A new connection to the endpoint that processes requests for refreshing the access token
     */
    HttpsURLConnection refreshTokenConnection = (HttpsURLConnection) (new URL(MSA_TOKEN_REFRESH_URL))
            .openConnection();
    refreshTokenConnection.setDoOutput(true);
    refreshTokenConnection.setRequestMethod("POST");
    refreshTokenConnection.setDoInput(true);
    refreshTokenConnection.setRequestProperty("Content-Type", TOKEN_REFRESH_CONTENT_TYPE);
    refreshTokenConnection.connect();
    OutputStream refreshTokenRequestStream = null;
    try {
        refreshTokenRequestStream = refreshTokenConnection.getOutputStream();
        String requestBody = MessageFormat.format(TOKEN_REFRESH_REQUEST_BODY, Constants.CLIENTID,
                TOKEN_REFRESH_REDIRECT_URL, refreshToken);
        refreshTokenRequestStream.write(requestBody.getBytes());
        refreshTokenRequestStream.flush();
    } finally {
        if (refreshTokenRequestStream != null) {
            refreshTokenRequestStream.close();
        }
    }
    if (refreshTokenConnection.getResponseCode() == 200) {
        return parseRefreshTokenResponse(refreshTokenConnection);
    } else {
        throw new Exception("The attempt to refresh the access token failed");
    }
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> get(String httpsURL) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;//from   w  w  w . j  a va  2s . c  o m
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:fr.qinder.api.APIGetter.java

protected HttpsURLConnection post(String sUrl, APIRequest request) {
    HttpsURLConnection urlConnection;
    URL url;/*w  w  w  . ja va  2  s.  c  o m*/
    try {
        url = new URL(sUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        if (request.getPosts().size() != 0) {
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(request.getPosts());
            OutputStream post = urlConnection.getOutputStream();
            entity.writeTo(post);
            post.flush();
        }
        urlConnection.connect();
    } catch (IOException e) {
        urlConnection = null;
    }
    return urlConnection;
}

From source file:com.kaixin.connect.Util.java

/**
 * http/*from  w  w w  . ja va  2s  .co m*/
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueStringbyte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            InputStreamopenUrl
 * @return JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

    if (!httpMethod.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // 
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + BOUNDARY + endLine).getBytes());
        os.write((encodePostBody(params, BOUNDARY)).getBytes());
        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; name=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
            }
        }

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> post(String httpsURL, String json) throws Exception {
    // Setup connection
    String result = "";
    URL url = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json; encoding=utf-8");
    con.setDoOutput(true);//from   www.  ja  v a  2  s. c o m
    OutputStream ops = con.getOutputStream();
    ops.write(json.getBytes("UTF-8"));
    ops.flush();
    ops.close();

    // Call wechat
    InputStream ins = con.getInputStream();
    InputStreamReader isr = new InputStreamReader(ins, "UTF-8");
    BufferedReader in = new BufferedReader(isr);

    // Read result
    String inputLine;
    StringBuilder sb = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        sb.append((new JSONObject(inputLine)).toString());
    }
    result = sb.toString();
    in.close();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:mediasearch.twitter.TwitterService.java

private HttpsURLConnection setUpConnection(String requestMethod, String endPointUrl, String authorization,
        String authValue) throws IOException {
    URL url = new URL(endPointUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setDoOutput(true);/*from w w  w  .  java2 s  . c  o m*/
    connection.setDoInput(true);
    connection.setRequestMethod(requestMethod);
    connection.setRequestProperty("Host", "api.twitter.com");
    connection.setRequestProperty("User-Agent", "NewSeedCloud");
    connection.setRequestProperty("Authorization", authorization + authValue);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
    //connection.setRequestProperty("Content-Length", "29");
    connection.setUseCaches(false);
    if (!authorization.contains("Bearer ")) {
        writeRequest(connection, "grant_type=client_credentials");
    }
    return connection;
}