List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:br.bireme.tb.URLS.java
/** * Given an url, loads its content (GET - method) * @param url url to be loaded/*from www. ja va 2 s .co m*/ * @return an array with the real location of the page (in case of redirect) * and its content. * @throws IOException */ public static String[] loadPageGet(final URL url) throws IOException { if (url == null) { throw new NullPointerException("url"); } System.out.print("loading page (GET) : [" + url + "]"); HttpURLConnection.setFollowRedirects(false); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING); connection.setRequestProperty("User-Agent", "curl/7.29.0"); connection.setRequestProperty("Accept", "*/*"); connection.connect(); int respCode = connection.getResponseCode(); final StringBuilder builder = new StringBuilder(); String location = url.toString(); while ((respCode >= 300) && (respCode <= 399)) { location = connection.getHeaderField("Location"); connection = (HttpURLConnection) new URL(location).openConnection(); respCode = connection.getResponseCode(); } final boolean respCodeOk = (respCode == 200); final BufferedReader reader; boolean skipLine = false; if (respCodeOk) { reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING)); } else { reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), DEFAULT_ENCODING)); } while (true) { String line = reader.readLine(); if (line == null) { break; } final String line2 = line.trim(); if (line2.startsWith("<!--")) { if (line2.endsWith("-->")) { continue; } skipLine = true; } else if (line2.endsWith("-->")) { skipLine = false; line = ""; } if (!skipLine) { builder.append(line); builder.append("\n"); } } reader.close(); connection.disconnect(); if (!respCodeOk) { throw new IOException("url=[" + url + "]\ncode=" + respCode + "\n" + builder.toString()); } //System.out.print("+"); System.out.println(" - OK"); return new String[] { location, builder.toString() }; }
From source file:it.polito.tellmefirst.web.rest.apimanager.RestManager.java
public String getStringFromAPI(String urlStr) { LOG.debug("[getStringFromAPI] - BEGIN"); String result = ""; try {/* ww w. j a v a 2 s .co m*/ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() != 200) { System.out.println(conn.getResponseCode() + "***********************************"); throw new IOException(conn.getResponseMessage()); } BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); result = sb.toString(); } catch (Exception e) { LOG.error("[getStringFromAPI] - EXCEPTION: ", e); } LOG.debug("[getStringFromAPI] - END"); return result; }
From source file:net.smartam.leeloo.controller.ResourceController.java
@RequestMapping public ModelAndView authorize(@ModelAttribute("oauthParams") OAuthParams oauthParams, HttpServletRequest req) { try {//from w w w . ja v a 2 s. c o m String tokenName = OAuth.OAUTH_TOKEN_DRAFT_0; if (Utils.SMART_GALLERY.equals(oauthParams.getApplication())) { tokenName = OAuth.OAUTH_TOKEN; } URL url = new URL(oauthParams.getResourceUrl() + "?" + tokenName + "=" + oauthParams.getAccessToken()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() == 200) { oauthParams.setResource(OAuthUtils.saveStreamAsString(conn.getInputStream())); } else { oauthParams.setErrorMessage( "Could not access resource: " + conn.getResponseCode() + " " + conn.getResponseMessage()); } } catch (IOException e) { oauthParams.setErrorMessage(e.getMessage()); } return new ModelAndView("resource"); }
From source file:com.stockita.popularmovie.utility.Utilities.java
/** * This will make a GET request to a RESTful web. * * @return String of JSON format//from w w w . ja v a 2s . c o m */ public static String getMovieData(String uri, Context context) { BufferedReader reader = null; HttpURLConnection con = null; try { URL url = new URL(uri); con = (HttpURLConnection) url.openConnection(); con.setReadTimeout(10000 /* milliseconds */); con.setConnectTimeout(15000 /* milliseconds */); con.setRequestMethod(REQUEST_METHOD_GET); con.connect(); int response = con.getResponseCode(); if (response < 200 || response > 299) { Log.e(LOG_TAG, "connection failed: " + response); sNetworkResponse = false; return null; } InputStream inputStream = con.getInputStream(); // Return null if no date if (inputStream == null) { Log.e(LOG_TAG, "inputStream returned null"); return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } // Return null if no data if (builder.length() == 0) { Log.e(LOG_TAG, "builder return null"); return null; } return builder.toString(); } catch (IOException e) { Log.e(LOG_TAG, e.toString()); sNetworkResponse = false; return null; } finally { try { if (reader != null) reader.close(); if (con != null) con.disconnect(); } catch (Exception e) { e.printStackTrace(); Log.e(LOG_TAG, e.toString()); } } }
From source file:com.kiwiteam.nomiddleman.TourPageActivity.java
/** * Checks if link is active//from w w w. jav a 2 s . com * @param urlString * @return * @throws MalformedURLException * @throws IOException */ public static int getResponseCode(String urlString) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setRequestMethod("GET"); huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"); huc.connect(); return huc.getResponseCode(); }
From source file:com.facebook.GraphErrorTest.java
@Test public void testAccessTokenResetOnTokenError() throws JSONException, IOException { AccessToken accessToken = mock(AccessToken.class); AccessToken.setCurrentAccessToken(accessToken); JSONObject errorBody = new JSONObject(); errorBody.put("message", "Invalid OAuth access token."); errorBody.put("type", "OAuthException"); errorBody.put("code", FacebookRequestErrorClassification.EC_INVALID_TOKEN); JSONObject error = new JSONObject(); error.put("error", errorBody); String errorString = error.toString(); HttpURLConnection connection = mock(HttpURLConnection.class); when(connection.getResponseCode()).thenReturn(400); GraphRequest request = mock(GraphRequest.class); when(request.getAccessToken()).thenReturn(accessToken); GraphRequestBatch batch = new GraphRequestBatch(request); assertNotNull(AccessToken.getCurrentAccessToken()); GraphResponse.createResponsesFromString(errorString, connection, batch); assertNull(AccessToken.getCurrentAccessToken()); }
From source file:com.cloudbees.workflow.Util.java
public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType) throws IOException { String jenkinsUrl = jenkins.getRootUrl(); URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/")); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); try {//from w w w.j ava 2 s . co m conn.setRequestMethod("POST"); // Set the crumb header, otherwise the POST may be rejected. NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins); conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue()); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } if (content != null) { byte[] bytes = content.getBytes(Charset.forName("UTF-8")); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); final OutputStream os = conn.getOutputStream(); try { os.write(bytes); os.flush(); } finally { os.close(); } } return conn.getResponseCode(); } finally { conn.disconnect(); } }
From source file:org.apache.hadoop.http.TestHttpServerLogs.java
@Test public void testLogsEnabled() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(CommonConfigurationKeysPublic.HADOOP_HTTP_LOGS_ENABLED, true); startServer(conf);/* w w w . ja v a 2 s .c o m*/ URL url = new URL("http://" + NetUtils.getHostPortString(server.getConnectorAddress(0)) + "/logs"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); assertEquals(HttpStatus.SC_OK, conn.getResponseCode()); }
From source file:com.telefonica.iot.perseo.Utils.java
/** * Makes an HTTP POST to an URL sending an body. The URL and body are * represented as String.//from ww w. j ava2s . com * * @param urlStr String representation of the URL * @param content Styring representation of the body to post * * @return if the request has been accompished */ public static boolean DoHTTPPost(String urlStr, String content) { try { URL url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoOutput(true); urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID)); urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD)); urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD)); urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD)); OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(), Charset.forName("UTF-8")); printout.write(content); printout.flush(); printout.close(); int code = urlConn.getResponseCode(); String message = urlConn.getResponseMessage(); logger.debug("action http response " + code + " " + message); if (code / 100 == 2) { InputStream input = urlConn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); for (String line; (line = reader.readLine()) != null;) { logger.info("action response body: " + line); } input.close(); return true; } else { logger.error("action response is not OK: " + code + " " + message); InputStream error = urlConn.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(error)); for (String line; (line = reader.readLine()) != null;) { logger.error("action error response body: " + line); } error.close(); return false; } } catch (MalformedURLException me) { logger.error("exception MalformedURLException: " + me); return false; } catch (IOException ioe) { logger.error("exception IOException: " + ioe); return false; } }
From source file:it.polito.tellmefirst.enhancer.NYTimesEnhancer.java
private String getResultFromAPI(String urlStr) { LOG.debug("[getResultFromAPI] - BEGIN"); String result = ""; try {/* w ww . jav a 2 s . c o m*/ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); result = sb.toString(); } catch (Exception e) { LOG.error("[getResultFromAPI] - EXCEPTION: ", e); } LOG.debug("[getResultFromAPI] - END"); return result; }