List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:gmusic.api.comm.HttpUrlConnector.java
@Override public final synchronized String dispatchGet(URI address) throws URISyntaxException, IOException { // HttpURLConnection connection = (HttpURLConnection) adjustAddress(address).toURL().openConnection(); // connection.setRequestMethod("GET"); // connection.setRequestProperty("Cookie", rawCookie); // if(authorizationToken != null) // {//ww w . j a va2s . c om // connection.setRequestProperty("Authorization", String.format("GoogleLogin auth=%1$s", authorizationToken)); // } HttpURLConnection connection = prepareConnection(address, false, "GET"); connection.connect(); if (connection.getResponseCode() != 200) { throw new IllegalStateException("Statuscode " + connection.getResponseCode() + " not supported"); } setCookie(connection); return IOUtils.toString(connection.getInputStream()); }
From source file:com.baidu.jprotobuf.rpc.client.SimpleHttpRequestExecutor.java
/** * Validate the given response as contained in the HttpURLConnection object, * throwing an exception if it does not correspond to a successful HTTP response. * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid * parsing the response body and trying to deserialize from a corrupted stream. * @param con the HttpURLConnection to validate * @throws IOException if validation failed * @see java.net.HttpURLConnection#getResponseCode() *//*from w ww.j a v a2s . c om*/ protected void validateResponse(HttpURLConnection con) throws IOException { if (con.getResponseCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + con.getResponseCode() + ", status message = [" + con.getResponseMessage() + "]"); } }
From source file:app.nichepro.fragmenttab.account.AbstractGetNameTask.java
/** * Contacts the user info server to get the profile of the user and extracts * the first name of the user from the profile. In order to authenticate * with the user info server the method first fetches an access token from * Google Play services./*from ww w . ja v a 2 s.c o m*/ * * @throws IOException * if communication with user info server failed. * @throws JSONException * if the response from the server could not be parsed. */ private String fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); String json = null; if (token == null) { // error has already been handled in fetchToken() return json; } URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token); HttpURLConnection con = (HttpURLConnection) url.openConnection(); int sc = con.getResponseCode(); if (sc == 200) { InputStream is = con.getInputStream(); // mActivity.googleLoginSuccess(readResponse(is)); json = readResponse(is); is.close(); return json; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); // onError("Server auth error, please try again.", null); error = "Server auth error, please try again."; Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return json; } else { // onError("Server returned the following error code: " + sc, null); error = "Server auth error, please try again."; return json; } }
From source file:com.creactiviti.piper.core.taskhandler.io.Download.java
@Override public Object handle(Task aTask) { try {/* w w w. ja v a2s. com*/ URL url = new URL(aTask.getRequiredString("url")); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() / 100 == 2) { File downloadedFile = File.createTempFile("download-", "", null); int contentLength = connection.getContentLength(); Consumer<Integer> progressConsumer = (p) -> eventPublisher.publishEvent(PiperEvent .of(Events.TASK_PROGRESSED, "taskId", ((TaskExecution) aTask).getId(), "progress", p)); try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); OutputStream os = new ProgressingOutputStream(new FileOutputStream(downloadedFile), contentLength, progressConsumer)) { copy(in, os); } return downloadedFile.toString(); } throw new IllegalStateException("Server returned: " + connection.getResponseCode()); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:com.example.admin.processingboilerplate.JsonIO.java
public static JSONObject pushJson(String requestURL, String jsonDataName, JSONObject json) { try {//from w ww. j a v a 2s. c o m String boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); //HttpURLConnection con = (HttpURLConnection) url.openConnection(); URLConnection uc = (url).openConnection(); HttpURLConnection con = requestURL.startsWith("https") ? (HttpsURLConnection) uc : (HttpURLConnection) uc; con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); con.setRequestProperty("User-Agent", USER_AGENT); OutputStream outputStream = con.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"" + "data" + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF); writer.append(json.toString()).append(CRLF); writer.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF); writer.close(); int status = con.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { StringBuilder sb = load(con); try { json = new JSONObject(sb.toString()); return json; } catch (JSONException e) { Log.e("loadJson", e.getMessage(), e); e.printStackTrace(); return new JSONObject(); } } else { throw new IOException("Server returned non-OK status: " + status); } } catch (IOException e) { e.printStackTrace(); } return new JSONObject(); }
From source file:URLMonitorPanel.java
public void run() { if (System.currentTimeMillis() - scheduledExecutionTime() > 5000) { // Let the next task do it return;/*from w w w.ja va 2s . c o m*/ } try { HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(1000); huc.setReadTimeout(1000); int code = huc.getResponseCode(); if (updater != null) updater.isAlive(true); } catch (Exception e) { if (updater != null) updater.isAlive(false); } }
From source file:com.cpp255.bookbarcode.DouBanBookInfoXmlParser.java
/** * ?isbn???/*from ww w .j av a 2 s . c o m*/ * * @param isbnNo * @return * @throws IOException */ public BookInfo fetchBookInfoByXML(String isbnNo) throws IOException { String requestUrl = ISBN_URL + isbnNo; URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); if (conn.getResponseCode() == RETURN_BOOKINFO_STATUS) { InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); return readBookInfo(sb.toString()); } return null; }
From source file:org.cytoscape.app.internal.net.server.AddAccessControlAllowOriginHeaderAfterResponseTest.java
@Test public void testAddAccessControlAllowOriginHeader() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/test$"); }/*from w ww . j av a2 s . c o m*/ public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html"); } }); httpd.addAfterResponse(new AddAccessControlAllowOriginHeaderAfterResponse()); httpd.start(); HttpURLConnection connection = null; final String url = "http://localhost:2611/test"; connection = connectToURL(url, "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*"); assertEquals(readConnection(connection), "test response ok"); httpd.stop(); }
From source file:org.cytoscape.app.internal.net.server.AddAllowOriginHeaderTest.java
@Test public void testAddAccessControlAllowOriginHeader() throws Exception { final CyHttpd httpd = (new CyHttpdFactoryImpl()).createHttpd(new LocalhostServerSocketFactory(2611)); final CyHttpResponseFactory responseFactory = new CyHttpResponseFactoryImpl(); httpd.addResponder(new CyHttpResponder() { public Pattern getURIPattern() { return Pattern.compile("^/test$"); }//from ww w. jav a 2 s . c o m public CyHttpResponse respond(CyHttpRequest request, Matcher matchedURI) { return responseFactory.createHttpResponse(HttpStatus.SC_OK, "test response ok", "text/html"); } }); httpd.addAfterResponse(new AddAllowOriginHeader()); httpd.start(); HttpURLConnection connection = null; final String url = "http://localhost:2611/test"; connection = connectToURL(url, "GET"); assertTrue(connection.getResponseCode() == HttpURLConnection.HTTP_OK); assertEquals(connection.getHeaderField("Access-Control-Allow-Origin"), "*"); assertEquals(readConnection(connection), "test response ok"); httpd.stop(); }