Example usage for javax.net.ssl HttpsURLConnection setDoInput

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

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:org.wso2.carbon.sample.service.EventsManagerService.java

public String performPostCall(String requestURL, Map<String, String> postDataParams)
        throws HttpException, IOException {

    URL url;/* www  .  j  a  va 2 s  .  co m*/
    String response = "";

    url = new URL(requestURL);

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(15000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(postDataParams));

    writer.flush();
    writer.close();
    os.close();
    int responseCode = conn.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "";
        throw new HttpException(responseCode + "");
    }

    return response;
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from   w w w. ja  v  a  2  s.  c  om*/
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.google.android.apps.picview.request.CachedWebRequestFetcher.java

/** 
 * Fetches the given URL from the web./*from w  ww .ja va  2s . com*/
 */
public String fetchFromWeb(URL url) {

    Log.d(TAG, "Fetching from web: " + url.toString());
    HttpsURLConnection conn = null;
    HttpResponse resp = null;
    try {
        conn = (HttpsURLConnection) url.openConnection();
        conn.setUseCaches(false);
        conn.setReadTimeout(30000); // 30 seconds. 
        conn.setDoInput(true);
        conn.addRequestProperty("GData-Version", "2");
        conn.connect();
        InputStream is = conn.getInputStream();
        return readStringFromStream(is);
    } catch (Exception e) {
        Log.v(TAG, readStringFromStream(conn.getErrorStream()));
        e.printStackTrace();
    }
    return null;
}

From source file:org.belio.service.gateway.AirtelCharging.java

private String sendXmlOverPost(String url, String xml) {
    StringBuffer result = new StringBuffer();
    try {/* ww  w.j  a  v  a  2s.co  m*/
        Launcher.LOG.info("======================xml==============");

        Launcher.LOG.info(xml.toString());

        //            String userPassword = "roamtech_KE:roamtech _KE!ibm123";
        //            URL url2 = new URL("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");

        String userPassword = "" + networkproperties.getProperty("air_info_u") + ":"
                + networkproperties.getProperty("air_info_p");
        URL url2 = new URL(url);

        // URLConnection urlc =  url.openConnection();
        URLConnection urlc = url2.openConnection();
        HttpsURLConnection conn = (HttpsURLConnection) urlc;
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("SOAPAction", "run");

        //            urlc.setDoOutput(true);
        //            urlc.setUseCaches(false);
        //            urlc.setAllowUserInteraction(false);
        conn.setRequestProperty("Authorization", "Basic " + new Base64().encode(userPassword.getBytes()));
        conn.setRequestProperty("Content-Type", "text/xml");

        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        // Write post data
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(xml);
        out.flush();
        out.close();
        BufferedReader aiResult = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        StringBuffer responseMessage = new StringBuffer();
        while ((line = aiResult.readLine()) != null) {
            responseMessage.append(line);
        }
        System.out.println(responseMessage);

        //urlc.s("POST");  
        //  urlc.setRequestProperty("SOAPAction", SOAP_ACTION);

        urlc.connect();

    }

    catch (MalformedURLException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }

    catch (IOException ex) {
        Logger.getLogger(AirtelCharging.class

                .getName()).log(Level.SEVERE, null, ex);
    }
    return result.toString();

    //        try {
    //            // String url = "https://selfsolve.apple.com/wcResults.do";
    //            HttpClient client = new DefaultHttpClient();
    //            HttpPost post = new HttpPost("https://41.223.58.133:8443/ChargingServiceFlowWeb/sca/ChargingExport1");
    //            // add header
    //            post.setHeader("User-Agent", USER_AGENT);
    //            post.setHeader("Content-type:", " text/xml");
    //            post.setHeader("charset", "utf-8");
    //            post.setHeader("Accept:", ",text/xml");
    //            post.setHeader("Cache-Control:", " no-cache");
    //            post.setHeader("Pragma:", " no-cache");
    //            post.setHeader("SOAPAction:", "run");
    //            post.setHeader("Content-length:", "xml");
    //            
    ////            String encoding = new Base64().encode((networkproperties.getProperty("air_charge_n") + ":"
    ////                    + networkproperties.getProperty("air_charge_p")).getBytes());
    //            String encoding = new Base64().encode( ("roamtech_KE:roamtech _KE!ibm123").getBytes());
    //            
    //            post.setHeader("Authorization", "Basic " + encoding);
    //
    //            // post.setHeader("Authorization: Basic ", "base64_encode(credentials)");
    //            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    //            
    //            urlParameters.add(new BasicNameValuePair("xml", xml));
    //            
    //            System.out.println("\n============================ : " + url);
    //
    ////            urlParameters.add(new BasicNameValuePair("srcCode", ""));
    ////            urlParameters.add(new BasicNameValuePair("phone", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentId", ""));
    ////            urlParameters.add(new BasicNameValuePair("itemName", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentDescription", ""));
    ////            urlParameters.add(new BasicNameValuePair("actualPrice", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentMediaType", ""));
    ////            urlParameters.add(new BasicNameValuePair("contentUrl", ""));
    //            post.setEntity(new UrlEncodedFormEntity(urlParameters));
    //            
    //            HttpResponse response = client.execute(post);
    //            Launcher.LOG.info("\nSending 'POST' request to URL : " + url);
    //            Launcher.LOG.info("Post parameters : " + post.getEntity());
    //            Launcher.LOG.info("Response Code : "
    //                    + response.getStatusLine().getStatusCode());
    //            
    //            BufferedReader rd = new BufferedReader(
    //                    new InputStreamReader(response.getEntity().getContent()));
    //            
    //            String line = "";
    //            while ((line = rd.readLine()) != null) {
    //                result.append(line);
    //            }
    //            
    //            System.out.println(result.toString());
    //        } catch (UnsupportedEncodingException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        } catch (IOException ex) {
    //            Launcher.LOG.info(ex.getMessage());
    //        }
}

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);/*  www .  j a  v a 2  s .  co 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:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;/*from  ww w . ja va 2  s  . co  m*/
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:org.croudtrip.activities.MainActivity.java

public void showUserInfoInNavigationDrawer() {

    // Get logged-in user and his data
    User user = AccountManager.getLoggedInUser(getApplicationContext());
    String firstName = (user == null || user.getFirstName() == null) ? "" : user.getFirstName();
    String lastName = (user == null || user.getLastName() == null) ? "" : user.getLastName();
    String email = (user == null || user.getEmail() == null) ? "" : user.getEmail();
    final String avatarUrl = (user == null || user.getAvatarUrl() == null) ? null : user.getAvatarUrl();
    Timber.i("Nav drawer avatarUrl is: " + avatarUrl);
    final MaterialAccount account = new MaterialAccount(this.getResources(), firstName + " " + lastName, email,
            R.drawable.profile, R.drawable.background_drawer);
    this.addAccount(account);
    // Download his avatar
    if (avatarUrl != null) {
        Observable.defer(new Func0<Observable<Bitmap>>() {
            @Override//from   ww  w  .ja v  a2 s . co m
            public Observable<Bitmap> call() {
                try {
                    URL url = new URL(avatarUrl);
                    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.connect();
                    InputStream input = connection.getInputStream();
                    return Observable.just(BitmapFactory.decodeStream(input));
                } catch (Exception e) {
                    return Observable.error(e);
                }
            }
        }).compose(new DefaultTransformer<Bitmap>()).subscribe(new Action1<Bitmap>() {
            @Override
            public void call(Bitmap avatar) {
                Timber.d("avatar is null " + (avatar == null));
                Timber.d("" + avatar.getWidth());
                account.setPhoto(avatar);
                notifyAccountDataChanged();
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                Timber.e(throwable, "failed to download avatar");
            }
        });
    }
}

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

/**
  * Run the web service request/*w w  w  .j  a v  a 2s. c o 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/*from   w  ww . j a  va 2 s  . 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();
    }
}

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

protected HttpsURLConnection post(String sUrl, APIRequest request) {
    HttpsURLConnection urlConnection;
    URL url;//from  w  w  w.j  a va2  s . c om
    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;
}