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:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from  w  w  w  . ja v  a2s  .  co m
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

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

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java

@Test
@Ignore//from w w w . j a va 2  s . com
public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception {

    useTestWorkspace("brouder_sylvie");
    login("george.washington", "1234");

    /*
     * upload the test workflow
     */
    MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE,
            new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE));
    MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload(
            "/workflows/import").accept(MediaType.ALL).session(httpSession);
    mockMultipartHttpServletRequestBuilder.file(mockMultipartFile);

    ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder);

    resultActions.andExpect(status().isCreated());

    String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString());
    Map<String, Object> workflow = Helper.deserialize(content, Map.class);
    assertNotNull("workflow is null", workflow);
    Integer workflowId = (Integer) workflow.get("id");

    /*
     * create a project and an experiment to associate the job for the workflow with
     * while doing that, make sure we save all the IDs associated to post it with the job
     */
    MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects")
            .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    Map<String, Object> map = Helper.deserialize(content, Map.class);
    Integer projectId = (Integer) map.get("id");

    mockHttpServletRequestBuilder = post("/experiments")
            .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId
                    + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}")
            .accept(MediaType.APPLICATION_JSON).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isCreated());

    content = resultActions.andReturn().getResponse().getContentAsString();
    map = Helper.deserialize(content, Map.class);
    Integer experimentId = (Integer) map.get("id");

    /*
     * create a job associated with the project, experiment and workflow we just created
     */
    mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString())
            .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString())
            .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);
    resultActions.andExpect(status().isOk());

    /*
     * forwarded to job/submit/jobId
     */
    String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl();
    mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * redirected to jobs/task/jobId
     */
    String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();
    mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession);
    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    /*
     * we're at UT1 in the workflow
     */
    String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1);
    TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task");
    String taskId = task.getId();

    String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28";
    String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654";

    // For buttton 1
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    //uriBuilder.queryParam("redirect_uri", "code");
    uriBuilder.queryParam("client_id", username);

    URL url = new URL(uriBuilder.build(true).toUriString());
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    String res = IOUtils.toString(connection.getInputStream());
    Map<String, Object> responseMap = Helper.deserialize(res, Map.class);
    String code = (String) responseMap.get("code");

    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("multiple", false);

    String uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // For Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize");
    uriBuilder.queryParam("response_type", "code");
    uriBuilder.queryParam("client_id", username);

    url = new URL(uriBuilder.build(true).toUriString());
    connection = (HttpsURLConnection) url.openConnection();
    userpass = username + ":" + password;
    basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    res = IOUtils.toString(connection.getInputStream());
    responseMap = Helper.deserialize(res, Map.class);
    code = (String) responseMap.get("code");

    // For button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback");
    uriBuilder.queryParam("jobId", Integer.parseInt(jobId));
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("multiple", true);

    uri = uriBuilder.build(true).toUriString() + "&code=" + code;
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    // Getting accessToken only from one button
    String accessToken = "";
    String[] urlParts = redirectedUrl.split("&");
    for (String urlPart : urlParts) {
        if (urlPart.contains("accessToken")) {
            String[] accessTokenPair = urlPart.split("=");
            accessToken = accessTokenPair[1];
            break;
        }
    }

    //Button 1
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile1");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //Button 2
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1);
    uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2);

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile2");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri);
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    //For getting Storage Files (an abstract button called browsefile3)
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile");
    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("multiple", true);
    uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory

    System.out.println(uriBuilder.build(true).toUriString());

    mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    redirectedUrl = resultActions.andReturn().getResponse().getContentAsString();

    System.out.println("Redirected to: " + redirectedUrl);

    //FileSelect
    uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback");
    uriBuilder.queryParam("fileId", 1);
    uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/");

    uriBuilder.queryParam("jobId", jobId);
    uriBuilder.queryParam("alias", templateId + ".browsefile3");
    uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8")
    uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8"));

    uri = uriBuilder.build(true).toUriString();
    uri = URLDecoder.decode(uri, "UTF-8");
    uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8");
    mockHttpServletRequestBuilder = get(uri).session(httpSession);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1";

    MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder(
            multipartBoundary);
    multiPartFileContentBuilder.addField("autoGenerated", "true");
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    multiPartFileContentBuilder.addField("isIframe", "true");
    multiPartFileContentBuilder.addField("experimentId", "");
    multiPartFileContentBuilder.addField("projectId", "");
    multiPartFileContentBuilder
            .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", "");
    multiPartFileContentBuilder
            .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", "");
    String taskContent = multiPartFileContentBuilder.build();

    // /rest/objectus post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/")
            .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "")
            .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().isOk());

    multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR";
    multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary);
    multiPartFileContentBuilder.addField("jobId", jobId);
    multiPartFileContentBuilder.addField("taskId", taskId);
    multiPartFileContentBuilder.addField("jsonToServer", "{}");
    taskContent = multiPartFileContentBuilder.build();

    // /jobs/task post call
    mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task")
            .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true")
            .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession);
    mockHttpServletRequestBuilder.content(taskContent);

    resultActions = mockMvc.perform(mockHttpServletRequestBuilder);

    resultActions.andExpect(status().is3xxRedirection());

    redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl();

    System.out.println("Redirected to: " + redirectedUrl);

    deleteDatasetEntries(templateId);
}

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params/* w w w  .j a v  a  2  s  .  com*/
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

        connection.setDoOutput(true);
        connection.setDoInput(true);

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

        if (connection != null)
            connection.disconnect();
        connection = null;
    }

    return answer;
}

From source file:org.exoplatform.services.videocall.AuthService.java

public String authenticate(VideoCallModel videoCallModel, String profile_id) {
    VideoCallService videoCallService = new VideoCallService();
    if (videoCallModel == null) {
        caFile = videoCallService.getPemCertInputStream();
        p12File = videoCallService.getP12CertInputStream();
        videoCallModel = videoCallService.getVideoCallProfile();
    } else {//from   w w  w  .java  2s  .  c o m
        caFile = videoCallModel.getPemCert();
        p12File = videoCallModel.getP12Cert();
    }

    if (videoCallModel != null) {
        domain_id = videoCallModel.getDomainId();
        clientId = videoCallModel.getAuthId();
        clientSecret = videoCallModel.getAuthSecret();
        passphrase = videoCallModel.getCustomerCertificatePassphrase();
    }
    String responseContent = null;
    if (StringUtils.isEmpty(passphrase))
        return null;
    if (caFile == null || p12File == null)
        return null;

    try {
        String userId = ConversationState.getCurrent().getIdentity().getUserId();
        SSLContext ctx = SSLContext.getInstance("SSL");
        URL url = null;
        try {
            StringBuilder urlBuilder = new StringBuilder();
            urlBuilder.append(authUrl).append("?client_id=" + clientId).append("&client_secret=" + clientSecret)
                    .append("&uid=weemo" + userId)
                    .append("&identifier_client=" + URLEncoder.encode(domain_id, "UTF-8"))
                    .append("&id_profile=" + URLEncoder.encode(profile_id, "UTF-8"));
            url = new URL(urlBuilder.toString());
        } catch (MalformedURLException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not create valid URL with base", e);
            }
        }
        HttpsURLConnection connection = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect", e);
            }
        }
        TrustManager[] trustManagers = getTrustManagers(caFile, passphrase);
        KeyManager[] keyManagers = getKeyManagers("PKCS12", p12File, passphrase);

        ctx.init(keyManagers, trustManagers, new SecureRandom());
        try {
            connection.setSSLSocketFactory(ctx.getSocketFactory());
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not configure request for POST", e);
            }
        }

        try {
            connection.connect();
        } catch (IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not connect to weemo", e);
            }
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sbuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sbuilder.append(line + "\n");
        }
        br.close();
        responseContent = sbuilder.toString();
        // Set new token key
        String tokenKey = "";
        if (!StringUtils.isEmpty(responseContent)) {
            JSONObject json = new JSONObject(responseContent);
            tokenKey = json.get("token").toString();
        } else {
            tokenKey = "";
        }
        videoCallService.setTokenKey(tokenKey);
    } catch (Exception ex) {
        LOG.error("Have problem during authenticating process.", ex);
        videoCallService.setTokenKey("");
    }
    return responseContent;
}

From source file:org.kontalk.upload.HTPPFileUploadConnection.java

private void setupClient(HttpsURLConnection conn, long length, String mime, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(//  w w w  . java 2 s. c  o  m
            ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Length", String.valueOf(length));
    conn.setRequestMethod("PUT");
}

From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java

/**
 * Upload a file to the given URL/* ww  w.jav  a2 s .  co m*/
 *
 * @param importUrl URL to be file upload
 * @param fileName  Name of the file to be upload
 * @throws IOException throws if connection issues occurred
 */
private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException {
    //open import API url connection and deploy the exported API
    URL url = new URL(importUrl);
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");

    FileBody fileBody = new FileBody(fileName);
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT);
    multipartEntity.addPart("file", fileBody);

    connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue());
    connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER,
            "Basic " + encodeCredentials(user, pass));
    OutputStream out = connection.getOutputStream();
    try {
        multipartEntity.writeTo(out);
    } finally {
        out.close();
    }
    int status = connection.getResponseCode();
    BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String temp;
    StringBuilder response = new StringBuilder();
    while ((temp = read.readLine()) != null) {
        response.append(temp);
    }
    Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response);
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_token(String urlString) throws IOException {

    String token = null;/*from w ww .java  2s .  c  om*/
    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        List<String> cookies1 = conn.getHeaderFields().get("Set-Cookie");

        for (int g = 0; g < cookies1.size(); g++) {
            Log.i(TAG, "Cookie_list: " + cookies1.get(g).toString());
            Cookie cookie;
            String[] cook = cookies1.get(g).toString().split(";");

            String[] subcook = cook[0].split("=");
            token = subcook[1];
            Log.i(TAG, "Sub Cook: " + subcook[1]);

            // subcook[1];
        }
    }
    //conn.disconnect();
    return token;
}

From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java

public TokenRequester getTokenRequester() {
    final OnlineControllerFragment self = this;
    final TokenRequester requester = new TokenRequester();
    requester.setRunnable(new Runnable() {
        @Override/*from w  w  w.  ja va 2 s  . c om*/
        public void run() {
            String url = self.getPreferencesEditor().getString("preference_server_login",
                    self.getString(R.string.preference_value_login));
            try {
                URL location = new URL(url);
                HttpsURLConnection s_connection = null;
                HttpURLConnection connection = null;
                InputStream input;
                int responseCode;
                boolean isHttps = url.contains("https");
                DataOutputStream writeStream;
                if (isHttps) {
                    s_connection = (HttpsURLConnection) location.openConnection();
                    s_connection.setRequestMethod("POST");
                    writeStream = new DataOutputStream(s_connection.getOutputStream());
                } else {
                    connection = (HttpURLConnection) location.openConnection();
                    connection.setRequestMethod("POST");
                    writeStream = new DataOutputStream(connection.getOutputStream());
                }
                StringBuilder urlParams = new StringBuilder();
                urlParams.append("name=").append(Build.MODEL).append("&email=").append(self.getOwnerEmail())
                        .append("&host=").append(true).append("&longitude=").append(self.longitude)
                        .append("&latitude=").append(self.latitude);
                writeStream.writeBytes(urlParams.toString());
                writeStream.flush();
                writeStream.close();
                if (isHttps) {
                    input = s_connection.getInputStream();
                    responseCode = s_connection.getResponseCode();
                } else {
                    input = connection.getInputStream();
                    responseCode = connection.getResponseCode();
                }
                if (input != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
                    String line;
                    String result = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    input.close();
                    requester.finishRequest(result);
                }
            } catch (IOException e) {
                //e.printStackTrace();
                requester.cancelRequest(e);
            }
        }
    });
    return requester;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Executes an HTTP request expecting a JSON response.
 *
 * @param url//from ww  w. j a  v a  2 s.c o  m
 * @param request_method
 * @param parameters
 * @return response from authentication server
 */
private JSONObject sendToServer(String url, String request_method, Map<String, String> parameters) {
    JSONObject json_response;
    HttpsURLConnection urlConnection = null;
    try {
        InputStream is = null;
        urlConnection = (HttpsURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod(request_method);
        String locale = Locale.getDefault().getLanguage() + Locale.getDefault().getCountry();
        urlConnection.setRequestProperty("Accept-Language", locale);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        DataOutputStream writer = new DataOutputStream(urlConnection.getOutputStream());
        writer.writeBytes(formatHttpParameters(parameters));
        writer.close();

        is = urlConnection.getInputStream();
        String plain_response = new Scanner(is).useDelimiter("\\A").next();
        json_response = new JSONObject(plain_response);
    } catch (ClientProtocolException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (IOException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (JSONException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyManagementException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (KeyStoreException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    } catch (CertificateException e) {
        json_response = getErrorMessage(urlConnection);
        e.printStackTrace();
    }

    return json_response;
}

From source file:org.kontalk.upload.KontalkBoxUploadConnection.java

private void setupClient(HttpsURLConnection conn, String mime, boolean encrypted, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate,
            acceptAnyCertificate));// w ww  .j ava 2s .  c om
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    if (encrypted)
        conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted");
    // bug caused by Lighttpd
    conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
}