List of usage examples for java.net HttpURLConnection HTTP_OK
int HTTP_OK
To view the source code for java.net HttpURLConnection HTTP_OK.
Click Source Link
From source file:Main.java
public static String UdatePlayerBT(String userName, String device) { String retStr = ""; try {//w w w.j a v a 2s.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:cc.vileda.sipgatesync.api.SipgateApi.java
public static String getToken(final String username, final String password) { try {//from w w w .j a va 2 s . c om final HttpURLConnection urlConnection = getConnection("/authorization/token"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); JSONObject request = new JSONObject(); request.put("username", username); request.put("password", password); OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); Log.d("SipgateApi", request.getString("username")); wr.write(request.toString()); wr.flush(); StringBuilder sb = new StringBuilder(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), "utf-8")); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); Log.d("SipgateApi", "" + sb.toString()); final JSONObject response = new JSONObject(sb.toString()); return response.getString("token"); } else { System.out.println(urlConnection.getResponseMessage()); } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * // www . j a va 2 s.c o m * ( ) * *******************************************************************************/ 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:Main.java
public static final String postData(String url, HashMap<String, String> params) { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); String outputString = null;//from w ww .j a v a2 s.c o m try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size()); Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); nameValuePairs.add(new BasicNameValuePair((String) pair.getKey(), (String) pair.getValue())); System.out.println(pair.getKey() + " = " + pair.getValue()); it.remove(); // avoids a ConcurrentModificationException } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) { byte[] result = EntityUtils.toByteArray(response.getEntity()); outputString = new String(result, "UTF-8"); } } catch (ClientProtocolException e) { Log.i(CLASS_NAME, "Client protocolException happened: " + e.getMessage()); } catch (IOException e) { Log.i(CLASS_NAME, "Client IOException happened: " + e.getMessage()); } catch (NetworkOnMainThreadException e) { Log.i(CLASS_NAME, "Client NetworkOnMainThreadException happened: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { Log.i(CLASS_NAME, "Unknown exeception: " + e.getMessage()); } return outputString; }
From source file:com.webcrawler.manager.impl.StorageManagerImpl.java
@Override public InputStream downloadImagesFromRemote(String imageURL) throws FileNotFoundException, IOException { contentLength = 0;/*w w w . j a va 2 s . c o m*/ URL url = new URL(imageURL); httpConnection = (HttpURLConnection) url.openConnection(); int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = httpConnection.getInputStream(); contentLength = httpConnection.getContentLength(); } else { throw new IOException("Error with url " + imageURL + ": " + responseCode); } return inputStream; }
From source file:com.francelabs.datafari.utils.SendHttpRequest.java
public static void sendGET(String url, String userAgent) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); int responseCode = con.getResponseCode(); logger.debug("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;/*from w w w.j av a 2s. c om*/ StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result logger.debug(response.toString()); } else { logger.debug("GET request not worked"); } }
From source file:Main.java
/** * On some devices we have to hack:/*ww w . j av a2 s. c o m*/ * http://developers.sun.com/mobility/reference/techart/design_guidelines/http_redirection.html * @return the resolved url if any. Or null if it couldn't resolve the url * (within the specified time) or the same url if response code is OK */ public static String getResolvedUrl(String urlAsString, int timeout) { try { URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // force no follow hConn.setInstanceFollowRedirects(false); // the program doesn't care what the content actually is !! // http://java.sun.com/developer/JDCTechTips/2003/tt0422.html hConn.setRequestMethod("HEAD"); // default is 0 => infinity waiting hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); hConn.connect(); int responseCode = hConn.getResponseCode(); hConn.getInputStream().close(); if (responseCode == HttpURLConnection.HTTP_OK) return urlAsString; String loc = hConn.getHeaderField("Location"); if (responseCode == HttpURLConnection.HTTP_MOVED_PERM && loc != null) return loc.replaceAll(" ", "+"); } catch (Exception ex) { } return ""; }
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);/*from w w w. j a v a 2s . c o m*/ conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceResult.java
/** * @param response/* w w w .j a v a 2 s . c om*/ */ public UploadSourceResult(HttpResponse response) { this.successful = (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK); this.response = response; }
From source file:com.google.cloud.runtime.jetty.util.HttpUrlUtil.java
/** * Wait for a server to be "up" by requesting a specific GET resource * that should be returned in status code 200. * <p>/* w ww. ja v a 2 s.c o m*/ * This will attempt a check for server up. * If any result other then response code 200 occurs, then * a 2s delay is performed until the next test. * Up to the duration/timeunit specified. * </p> * * @param uri the URI to request * @param duration the time duration to wait for server up * @param unit the time unit to wait for server up */ public static void waitForServerUp(URI uri, int duration, TimeUnit unit) { System.err.println("Waiting for server up: " + uri); boolean waiting = true; long expiration = System.currentTimeMillis() + unit.toMillis(duration); while (waiting && System.currentTimeMillis() < expiration) { try { System.out.print("."); HttpURLConnection http = openTo(uri); int statusCode = http.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { log.log(Level.FINER, "Waiting 2s for next attempt"); TimeUnit.SECONDS.sleep(2); } else { waiting = false; } } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URI: " + uri.toString()); } catch (IOException e) { log.log(Level.FINEST, "Ignoring IOException", e); } catch (InterruptedException ignore) { // ignore } } System.err.println(); System.err.println("Server seems to be up."); }