Example usage for java.net HttpURLConnection connect

List of usage examples for java.net HttpURLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:com.qsoft.components.gallery.utils.GalleryUtils.java

private static InputStream OpenHttpConnection(String strURL) throws IOException {
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

    try {//  www. j a  v  a  2 s .co  m
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        Log.e("error", ex.toString());
    }
    return inputStream;
}

From source file:bluevia.SendSMS.java

public static void sendBlueViaSMS(String user_email, String phone_number, String sms_message) {
    try {/*from w w w .  j a va  2  s.  co  m*/

        Properties blueviaAccount = Util.getNetworkAccount(user_email, "BlueViaAccount");
        if (blueviaAccount != null) {
            String consumer_key = blueviaAccount.getProperty("BlueViaAccount.consumer_key");
            String consumer_secret = blueviaAccount.getProperty("BlueViaAccount.consumer_secret");
            String access_key = blueviaAccount.getProperty("BlueViaAccount.access_key");
            String access_secret = blueviaAccount.getProperty("BlueViaAccount.access_secret");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret);
            consumer.setMessageSigner(new HmacSha1MessageSigner());
            consumer.setTokenWithSecret(access_key, access_secret);

            URL apiURI = new URL("https://api.bluevia.com/services/REST/SMS/outbound/requests?version=v1");
            HttpURLConnection request = (HttpURLConnection) apiURI.openConnection();

            request.setRequestProperty("Content-Type", "application/json");
            request.setRequestMethod("POST");
            request.setDoOutput(true);

            consumer.sign(request);
            request.connect();

            String smsTemplate = "{\"smsText\": {\n  \"address\": {\"phoneNumber\": \"%s\"},\n  \"message\": \"%s\",\n  \"originAddress\": {\"alias\": \"%s\"},\n}}";
            String smsMsg = String.format(smsTemplate, phone_number, sms_message, access_key);

            OutputStream os = request.getOutputStream();
            os.write(smsMsg.getBytes());
            os.flush();

            int rc = request.getResponseCode();

            if (rc == HttpURLConnection.HTTP_CREATED)
                log.info(String.format("SMS sent to %s. Text: %s", phone_number, sms_message));
            else
                log.severe(String.format("Error %d sending SMS:%s\n", rc, request.getResponseMessage()));
        } else
            log.warning("BlueVia Account seems to be not configured!");

    } catch (Exception e) {
        log.severe(String.format("Exception sending SMS: %s", e.getMessage()));
    }
}

From source file:hackathon.openrice.CardsActivity.java

public static Bitmap getBitmapFromURL(String src) {
    try {/*w w w  . j  a  v a2s .c om*/
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        //e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static String simplePost(String url, Bundle params, String method)
        throws MalformedURLException, IOException {
    OutputStream os;//from  w  w  w  .  ja v a  2 s.  c  om

    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");

    conn.connect();

    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(encodePostParams(params).getBytes());
    os.flush();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;/* w  w w  . j av a  2s .c  o  m*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != HttpStatus.SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:Main.java

public static String callJsonAPI(String urlString) {
    // Use HttpURLConnection as per Android 6.0 spec, instead of less efficient HttpClient
    HttpURLConnection urlConnection = null;
    StringBuilder jsonResult = new StringBuilder();

    try {//from w w w.j a  v  a  2s  . co  m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(TIMEOUT_CONNECTION);
        urlConnection.setReadTimeout(TIMEOUT_READ);
        urlConnection.connect();

        int status = urlConnection.getResponseCode();

        switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;
            while ((line = br.readLine()) != null) {
                jsonResult.append(line).append("\n");
            }
            br.close();
        }
    } catch (MalformedURLException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } catch (IOException e) {
        System.err.print(e.getMessage());
        return e.getMessage();
    } finally {
        if (urlConnection != null) {
            try {
                urlConnection.disconnect();
            } catch (Exception e) {
                System.err.print(e.getMessage());
            }
        }
    }
    return jsonResult.toString();
}

From source file:mashberry.com500px.util.Api_Parser.java

/*******************************************************************************
  * //from w w w . ja v a2s . c  o  m
  *    (  )
  * 
  *******************************************************************************/
public static String get_second_detail(final int position, final String string, final int url_image_size,
        final int comments, final int comments_page) {
    String returnStr = "success";
    String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size
    /*+ "&comments="   + comments
    + "&comments_page="   + comments_page*/
            + "&consumer_key=" + Var.consumer_key;
    try {
        URL url = new URL(urlStr);
        URLConnection uc = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) uc;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        httpConn.setConnectTimeout(10000);
        int response = httpConn.getResponseCode();

        if (response == HttpURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            String userPictureOpt = "8";
            String result = convertStreamToString(in);
            JSONObject jObject = new JSONObject(result);
            JSONObject jsonObject = jObject.getJSONObject("photo");

            //            Log.i(TAG, "jsonObject " + jsonObject);

            Var.detail_nameMap.put(position, jsonObject.getString("name"));
            Var.detail_locationMap.put(position, jsonObject.getString("location"));
            Var.detail_ratingMap.put(position, jsonObject.getString("rating"));
            Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed"));
            Var.detail_votesMap.put(position, jsonObject.getString("votes_count"));
            Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count"));
            Var.detail_descriptionMap.put(position, jsonObject.getString("description"));
            Var.detail_cameraMap.put(position, jsonObject.getString("camera"));
            Var.detail_lensMap.put(position, jsonObject.getString("lens"));
            Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length"));
            Var.detail_isoMap.put(position, jsonObject.getString("iso"));
            Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed"));
            Var.detail_apertureMap.put(position, jsonObject.getString("aperture"));
            Var.detail_categoryMap.put(position, jsonObject.getString("category"));
            Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded"));
            Var.detail_takenMap.put(position, jsonObject.getString("taken_at"));
            Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type"));

            JSONObject jsonuser = jsonObject.getJSONObject("user");
            Var.detail_user_nameMap.put(position, jsonuser.getString("fullname"));
            Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url"));

            //     ( . .)
            /*JSONArray jsonArray = jObject.getJSONArray("comments");
            for(int i=0 ; i<jsonArray.length() ; i++){
               Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id"));
               Var.comment_body.add(jsonArray.getJSONObject(i).getString("body"));
                       
                JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user");
                Var.comment_fullname.add(jsonuser.getString("fullname"));
                Var.comment_userpic_url.add(jsonuser.getString("userpic_url"));
            }*/

            /*            Log.i("Main", "feature   " +feature);
                        Log.i("Main", "filters   " +filters);
                        Log.i("Main", "categoryArr   " +Var.categoryArr);
                        Log.i("Main", "idArr   " +Var.idArr);
                        Log.i("Main", "image_urlArr   " +Var.image_urlArr);
                        Log.i("Main", "nameArr   " +Var.nameArr);
                        Log.i("Main", "ratingArr   " +Var.ratingArr);
                        Log.i("Main", "user_firstnameArr   " +Var.user_firstnameArr);
                        Log.i("Main", "user_fullnameArr   " +Var.user_fullnameArr);
                        Log.i("Main", "user_lastnameArr   " +Var.user_lastnameArr);
                        Log.i("Main", "user_upgrade_statusArr   " +Var.user_upgrade_statusArr);
                        Log.i("Main", "user_usernameArr   " +Var.user_usernameArr);
                        Log.i("Main", "user_userpic_urlArr   " +Var.user_userpic_urlArr);*/
        } else {
            returnStr = "not response";
            return returnStr;
        }
    } catch (Exception e) {
        e.printStackTrace();
        returnStr = "not response";
        return returnStr;
    }
    return returnStr;
}

From source file:Main.java

private static InputStream getInputStreamFromUrl_V9(Context paramContext, String paramString) {
    if (confirmDownload(paramContext, paramString)) {
        try {//from  w  ww. j av  a2s .  c  o  m

            URL localURL = new URL(paramString);
            HttpURLConnection localHttpURLConnection2 = (HttpURLConnection) localURL.openConnection();
            localHttpURLConnection2.setRequestProperty("Accept-Charset", "UTF-8");
            localHttpURLConnection2.setReadTimeout(30000);
            localHttpURLConnection2.setConnectTimeout(30000);
            localHttpURLConnection2.setRequestMethod("GET");
            localHttpURLConnection2.setDoInput(true);
            localHttpURLConnection2.connect();
            return localHttpURLConnection2.getInputStream();

        } catch (Throwable localThrowable) {

            localThrowable.printStackTrace();
            return null;

        }
    } else {
        return null;
    }
}

From source file:com.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;/*from w ww.j ava  2  s  .c  o  m*/
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:dictinsight.utils.io.HttpUtils.java

public static List<String> getSvnConfServer(String url) {
    BufferedReader reader = null;
    HttpURLConnection connection = null;
    List<String> seedList = new ArrayList<String>();
    try {//from  ww w .  j a v  a  2  s  .  c  om
        URL srcUrl = new URL(url);
        connection = (HttpURLConnection) srcUrl.openConnection();
        connection.setConnectTimeout(1000 * 10);
        connection.connect();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rec;
        while ((rec = reader.readLine()) != null) {
            seedList.add(rec);
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + " error!");
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null)
            connection.disconnect();
    }
    return seedList;
}