List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:com.firsttry.mumbaiparking.helpers.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. * @throws IOException if communication with user info server failed. * @throws JSONException if the response from the server could not be parsed. *///w w w . j a v a 2 s .co m private void fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); if (token == null) { // error has already been handled in fetchToken() return; } 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(); String name = getFirstName(readResponse(is)); mActivity.show(name); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); onError("Server auth error, please try again.", null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return; } else { onError("Server returned the following error code: " + sc, null); return; } }
From source file:com.taobao.diamond.server.controller.CheckController.java
public int checkStatusCode(String sURL) { try {/*from w w w. ja va 2 s.c o m*/ URL url = new URL(sURL); URLConnection conn = url.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection httpUrl = (HttpURLConnection) conn; return httpUrl.getResponseCode(); } return -1; } catch (Exception e) { return -1; } }
From source file:com.photon.phresco.framework.actions.forum.Forum.java
public String forum() { if (S_LOGGER.isDebugEnabled()) S_LOGGER.debug("entered forumIndex()"); if (debugEnabled) { S_LOGGER.debug("Entering Method Forum.forum()"); }/*from www .ja v a2 s . c o m*/ try { ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator(); String serviceUrl = administrator.getJforumPath(); User sessionUserInfo = (User) getHttpSession().getAttribute(REQ_USER_INFO); // Credentials credentials = sessionUserInfo.getCredentials(); Credentials credentials = null; String username = credentials.getUsername(); byte[] usernameEncode = Base64.encodeBase64(username.getBytes()); String encodedUsername = new String(usernameEncode); String password = credentials.getPassword(); getHttpRequest().setAttribute(REQ_USER_NAME, encodedUsername); getHttpRequest().setAttribute(REQ_PASSWORD, password); URL sonarURL = new URL(serviceUrl); HttpURLConnection connection = (HttpURLConnection) sonarURL.openConnection(); int responseCode = connection.getResponseCode(); if (responseCode != 200) { getHttpRequest().setAttribute(REQ_ERROR, "Help is not available"); return HELP; } StringBuilder sb = new StringBuilder(); sb.append(serviceUrl); sb.append(JFORUM_PARAMETER_URL); sb.append(JFORUM_USERNAME); sb.append(encodedUsername); sb.append(JFORUM_PASSWORD); sb.append(password); getHttpRequest().setAttribute(REQ_JFORUM_URL, sb.toString()); } catch (Exception e) { if (debugEnabled) { S_LOGGER.error( "Entered into catch block of Forum.forum()" + FrameworkUtil.getStackTraceAsString(e)); } } return HELP; }
From source file:com.vn.apksfull.task.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. * @throws IOException if communication with user info server failed. * @throws JSONException if the response from the server could not be parsed. */// www .j a va 2 s. c om private void fetchNameFromProfileServer() throws IOException, JSONException { String token = fetchToken(); if (token == null) { // error has already been handled in fetchToken() return; } 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(); GOOGLE_USER_DATA = readResponse(is); //mActivity.show("Hello " + name + "!"); Log.d(TAG, GOOGLE_USER_DATA); is.close(); return; } else if (sc == 401) { GoogleAuthUtil.invalidateToken(mActivity, token); onError("Server auth error, please try again.", null); Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream())); return; } else { onError("Server returned the following error code: " + sc, null); return; } }
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected void verifyResponseStatus(HttpURLConnection con) throws IOException { if (con.getResponseCode() / 100 != 2) { String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' ' + con.getResponseMessage(); InputStream es = con.getErrorStream(); String ct = con.getContentType(); if (ct != null) { HttpHeader contentType = HttpHeader.parse(ct); if (contentType.value.equals("application/json")) { // if the error is JSON, parse it if (es != null) { JSONObject error = JSONObject .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8"))); throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(), con.getURL()); }/*w w w.j av a 2 s . com*/ } } if (es != null) msg += "\n" + IOUtils.toString(es); throw new IOException(msg); } }
From source file:com.onesignal.OneSignalRestClient.java
private static void makeRequest(String url, String method, JSONObject jsonBody, ResponseHandler responseHandler) { HttpURLConnection con = null; int httpResponse = -1; String json = null;//from w w w . j a va 2 s .c o m try { con = (HttpURLConnection) new URL(BASE_URL + url).openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(TIMEOUT); con.setReadTimeout(TIMEOUT); if (jsonBody != null) con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestMethod(method); if (jsonBody != null) { String strJsonBody = jsonBody.toString(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " SEND JSON: " + strJsonBody); byte[] sendBytes = strJsonBody.getBytes("UTF-8"); con.setFixedLengthStreamingMode(sendBytes.length); OutputStream outputStream = con.getOutputStream(); outputStream.write(sendBytes); } httpResponse = con.getResponseCode(); InputStream inputStream; Scanner scanner; if (httpResponse == HttpURLConnection.HTTP_OK) { inputStream = con.getInputStream(); scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, method + " RECEIVED JSON: " + json); if (responseHandler != null) responseHandler.onSuccess(json); } else { inputStream = con.getErrorStream(); if (inputStream == null) inputStream = con.getInputStream(); if (inputStream != null) { scanner = new Scanner(inputStream, "UTF-8"); json = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : ""; scanner.close(); OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " RECEIVED JSON: " + json); } else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " HTTP Code: " + httpResponse + " No response body!"); if (responseHandler != null) responseHandler.onFailure(httpResponse, json, null); } } catch (Throwable t) { if (t instanceof java.net.ConnectException || t instanceof java.net.UnknownHostException) OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "Could not send last request, device is offline. Throwable: " + t.getClass().getName()); else OneSignal.Log(OneSignal.LOG_LEVEL.WARN, method + " Error thrown from network stack. ", t); if (responseHandler != null) responseHandler.onFailure(httpResponse, null, t); } finally { if (con != null) con.disconnect(); } }
From source file:com.sun.socialsite.pojos.App.java
public static App readFromURL(URL url) throws Exception { HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(false);//from w ww . j a v a 2s.c o m // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } con.connect(); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException(con.getResponseMessage()); } InputStream in = con.getInputStream(); return readFromStream(in, url); }
From source file:com.none.tom.simplerssreader.net.FeedDownloader.java
@SuppressWarnings("ConstantConditions") public static InputStream getInputStream(final Context context, final String feedUrl) { final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class); final NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK); LogUtils.logError("No network connection"); return null; }// w w w . jav a 2s. co m URL url; try { url = new URL(feedUrl); } catch (final MalformedURLException e) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e); return null; } final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context); final boolean useHttpTorProxy = networkPrefs[0]; final boolean httpsOnly = networkPrefs[1]; final boolean followRedir = networkPrefs[2]; for (int nrRedirects = 0;; nrRedirects++) { if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS); LogUtils.logError("Too many redirects"); return null; } HttpURLConnection conn = null; try { if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY); LogUtils.logError("Attempting insecure connection"); return null; } if (useHttpTorProxy) { conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT))); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name()); conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT); conn.connect(); final int responseCode = conn.getResponseCode(); switch (responseCode) { case HttpURLConnection.HTTP_OK: return getInputStream(conn.getInputStream()); case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case HTTP_TEMP_REDIRECT: if (followRedir) { final String location = conn.getHeaderField("Location"); url = new URL(url, location); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) { SharedPrefUtils.updateSubscriptionUrl(context, url.toString()); } continue; } ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED); LogUtils.logError("Couldn't follow redirect"); return null; default: if (responseCode < 0) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE); LogUtils.logError("No valid HTTP response"); return null; } else if (responseCode >= 400 && responseCode <= 500) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT); } else if (responseCode >= 500 && responseCode <= 600) { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED); } LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage()); return null; } } catch (final IOException e) { if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable")) || e instanceof SocketTimeoutException || e instanceof UnknownHostException) { ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e); } else { ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e); } return null; } finally { if (conn != null) { conn.disconnect(); } } } }
From source file:eu.geopaparazzi.library.network.NetworkUtilities.java
/** * Sends a string via POST to a given url. * //from w ww . j ava2s . c om * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @return the response. * @throws Exception */ public static String sendPost(String urlStr, String string, String user, String password) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } catch (Exception e) { e.printStackTrace(); throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.ris.mobile.ecloud.util.AbFileUtil.java
/** * ???xx.??./*from ww w. jav a 2 s. c o m*/ * @param connection * @return ?? */ public static String getRealFileName(HttpURLConnection connection) { String name = null; try { if (connection == null) { return name; } if (connection.getResponseCode() == 200) { for (int i = 0;; i++) { String mime = connection.getHeaderField(i); if (mime == null) { break; } // "Content-Disposition","attachment; filename=1.txt" // Content-Length if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase()); if (m.find()) { return m.group(1).replace("\"", ""); } } } } } catch (Exception e) { e.printStackTrace(); //AbLogUtil.e(AbFileUtil.class, "???"); } return name; }