List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;//from ww w.j av a 2 s .c o m URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from//from w w w.j a v a 2 s.com * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:com.magnet.tools.tests.MagnetToolStepDefs.java
@Then("The server at \"([^\"]*)\" is down$") public static void _the_server_at_is_down(String endpointUrl) { try {//ww w .j av a 2 s. com HttpURLConnection connection = (HttpURLConnection) new URL(endpointUrl).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setRequestMethod("GET"); connection.getResponseCode(); Assert.fail("the endpoint " + endpointUrl + " should not have been available"); } catch (MalformedURLException e) { throw new AssertionError(e); } catch (IOException e) { // this is what we are hoping for.. } }
From source file:Main.java
public static int sendMessage(String auth_token, String registrationId, String message) throws IOException { StringBuilder postDataBuilder = new StringBuilder(); postDataBuilder.append(PARAM_REGISTRATION_ID).append("=").append(registrationId); postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=").append("0"); postDataBuilder.append("&").append("data.payload").append("=") .append(URLEncoder.encode("Lars war hier", UTF8)); byte[] postData = postDataBuilder.toString().getBytes(UTF8); // Hit the dm URL. URL url = new URL("https://android.clients.google.com/c2dm/send"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);/* ww w . jav a 2 s . c om*/ conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(postData.length)); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth_token); OutputStream out = conn.getOutputStream(); out.write(postData); out.close(); int responseCode = conn.getResponseCode(); return responseCode; }
From source file:com.oracle.jes.samples.hellostorage.IptoGeo.java
public static String getCurrentIPAddress2() throws MalformedURLException, IOException { HttpURLConnection conn = (HttpURLConnection) (new URL("http://ifconfig.me/ip").openConnection()); //1 HttpClient httpclient = HttpClientBuilder.create().build(); //1 HttpGet g1 = new HttpGet("http://ifconfig.me/ip"); //1 HttpResponse res = httpclient.execute(g1); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); //1BufferedReader reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); String response = reader.readLine(); if (conn.getResponseCode() == 200) { return response.trim(); } else {//from w w w . j a v a 2s. c om return null; } //1 return response; }
From source file:com.polyvi.xface.http.XHttpWorker.java
/** * url???/*from ww w.j av a2 s. c o m*/ * * @param url * [in] * @return */ public static boolean isServerAccessable(String url) { boolean usable = false; try { URL urlCon = new URL(url); HttpURLConnection httpUrl = (HttpURLConnection) urlCon.openConnection(); httpUrl.setConnectTimeout(SERVER_CONNECT_TIMEOUT); httpUrl.setReadTimeout(SERVER_CONNECT_TIMEOUT); if (httpUrl.getResponseCode() == HttpURLConnection.HTTP_OK) { usable = true; return usable; } } catch (IOException e) { usable = false; e.printStackTrace(); } return usable; }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * //ww w .j a v a 2s . c om * ( ) * *******************************************************************************/ public static String get_first_detail(final String url_feature, final int url_image_size, final String url_category, final int url_page, int image_no) { String returnStr = "success"; String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only=" + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key + "&rpp=" + image_no; try { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) uc; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setConnectTimeout(10000); httpConn.setRequestMethod("GET"); httpConn.connect(); int response = httpConn.getResponseCode(); Main.progressBar_process(50); if (response == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream(); String smallImageOpt = "3"; // (8 1/8 ) String largeImageOpt = "0"; String userPictureOpt = "8"; String result = convertStreamToString(in); JSONObject jObject = new JSONObject(result); JSONArray jsonArray = jObject.getJSONArray("photos"); Main.progressBar_process(75); if (jsonArray.length() == 0) { returnStr = "no results"; } else { for (int i = 0; i < jsonArray.length(); i++) { Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category")); Var.idArr.add(jsonArray.getJSONObject(i).getString("id")); String smallImage = jsonArray.getJSONObject(i).getString("image_url"); String largeImage = largeImageOpt + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg"; Var.imageSmall_urlArr.add(smallImageOpt + smallImage); Var.imageLarge_urlArr.add(largeImage); Var.nameArr.add(jsonArray.getJSONObject(i).getString("name")); Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating")); JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user"); Var.user_firstnameArr.add(jsonuser.getString("firstname")); Var.user_fullnameArr.add(jsonuser.getString("fullname")); Var.user_lastnameArr.add(jsonuser.getString("lastname")); Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status")); Var.user_usernameArr.add(jsonuser.getString("username")); Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url")); Main.progressBar_process(75 + (15 * i / jsonArray.length())); } } // Log.i("Main", "urlStr " +urlStr); // Log.i("Main", "url_feature " +url_feature); // Log.i("Main", "categoryArr " +Var.categoryArr); // Log.i("Main", "idArr " +Var.idArr); // Log.i("Main", "imageLarge_urlArr " +Var.imageLarge_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:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendGet(String url) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;/* w w w . j a va2s .co m*/ try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } else { throw new IOException("Response Code: " + responseCode); } return response.toString(); } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * //from w w w . j a va 2 s .com * ( ) * *******************************************************************************/ 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:com.appdynamics.common.RESTClient.java
public static void sendPost(String urlString, String input, String apiKey) { try {//ww w . j a v a 2 s. c o m URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((apiKey).getBytes()))); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.info("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.info(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }