List of usage examples for java.net HttpURLConnection getResponseCode
public int getResponseCode() throws IOException
From source file:Main.java
public static String UpdateScore(String userName, int br) { String retStr = ""; try {/*from www . j a va 2 s. c o m*/ URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("broj", br); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:com.chiorichan.util.WebUtils.java
public static boolean sendTracking(String category, String action, String label) { String url = "http://www.google-analytics.com/collect"; try {//from www .jav a 2 s . c om URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return true; } catch (IOException e) { return false; } }
From source file:com.dream.library.utils.AbFileUtil.java
/** * ???xx.??./*from w ww. j a v 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(); AbLog.e("???"); } return name; }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;//from w ww. ja v a2 s.c o m r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean isURLAlive(String url) throws IOException { try {//from ww w . j a v a 2 s .c o m // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false // since "index" may auto load default archive, attach it to session, and redirect to "info" page, // we need to maintain the session across the pages. // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); out.println("Testing for already running ePADD by probing " + url); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); if (u.getResponseCode() == 200) { u.disconnect(); out.println("ePADD is already running!"); return true; } u.disconnect(); } catch (ConnectException ce) { } out.println("Good, ePADD is not already running"); return false; }
From source file:Main.java
public static String UdatePlayerBT(String userName, String device) { String retStr = ""; try {//from ww w . ja v a 2 s.c o m URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/PostaviBTdevice.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(10000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); Log.e("http", "por1"); JSONObject data = new JSONObject(); data.put("username", userName); data.put("bt_device", device); Log.e("http", "por3"); Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString()); String query = builder.build().getEncodedQuery(); Log.e("http", "por4"); OutputStream os = conn.getOutputStream(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bw.write(query); Log.e("http", "por5"); bw.flush(); bw.close(); os.close(); int responseCode = conn.getResponseCode(); Log.e("http", String.valueOf(responseCode)); if (responseCode == HttpURLConnection.HTTP_OK) { retStr = inputStreamToString(conn.getInputStream()); } else retStr = String.valueOf("Error: " + responseCode); Log.e("http", retStr); } catch (Exception e) { Log.e("http", "greska"); } return retStr; }
From source file:de.langerhans.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/* ww w .j a va2s .c om*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rate = o.optString(field, null); if (rate != null) { try { final double btcRate = Double .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString()); DecimalFormat df = new DecimalFormat("#.########"); df.setRoundingMode(RoundingMode.HALF_UP); DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); dfs.setGroupingSeparator(','); df.setDecimalFormatSymbols(dfs); final Fiat dogeRate = Fiat.parseFiat(currencyCode, df.format(btcRate * dogeBtcConversion)); if (dogeRate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source)); break; } } catch (final NumberFormatException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static int post(String url, JSONObject json, String username, String password) throws IOException { HttpURLConnection conn = createConnection(url, username, password); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/json"); byte[] jsonBytes = json.toString().getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length)); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(jsonBytes);//from w w w . j ava 2s. c o m out.flush(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048); for (String line = reader.readLine(); line != null; line = reader.readLine()) { } out.close(); int responseCode = 0; responseCode = conn.getResponseCode(); return responseCode; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * /*from ww w .j ava 2s . c o m*/ * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:edu.stanford.epadd.launcher.Splash.java
private static boolean killRunningServer(String url) throws IOException { try {//from www . jav a2 s . c om // attempt to fetch the page // throws a connect exception if the server is not even running // so catch it and return false // String http = url + "exit.jsp?message=Shutdown%20request%20from%20a%20different%20instance%20of%20ePADD"; // version num spaces and brackets screw up the URL connection // actually this should not be a HTTP connection, it can be simply any connection out.println("Sending a kill request to " + url); HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection(); u.connect(); if (u.getResponseCode() == 200) { u.disconnect(); return true; } u.disconnect(); } catch (ConnectException ce) { err.println("Warning: unable to kill running server: " + ce); } return false; }