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:com.stackmob.example.geopoints.WriteGeo.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { LoggerService logger = serviceProvider.getLoggerService(WriteGeo.class); Map<String, SMObject> feedback = new HashMap<String, SMObject>(); Map<String, String> errMap = new HashMap<String, String>(); String user = ""; String latitude = ""; String longitude = ""; JSONParser parser = new JSONParser(); try {/*from w ww . j a v a 2 s . c o m*/ Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; user = (String) jsonObject.get("user_name"); latitude = (String) jsonObject.get("Latitude"); longitude = (String) jsonObject.get("Longitude"); } catch (ParseException pe) { logger.error(pe.getMessage(), pe); return Util.badRequestResponse(errMap, pe.getMessage()); } if (Util.hasNulls(user, latitude, longitude)) { return Util.badRequestResponse(errMap, "Please fill in all parameters correctly"); } DataService ds = serviceProvider.getDataService(); List<SMUpdate> update = new ArrayList<SMUpdate>(); Map<String, SMValue> geoPoint = new HashMap<String, SMValue>(); SMObject result; try { geoPoint.put("lat", new SMDouble(Double.parseDouble(latitude))); geoPoint.put("lon", new SMDouble(Double.parseDouble(longitude))); update.add(new SMSet("position", new SMObject(geoPoint))); } catch (NumberFormatException nfe) { logger.error(nfe.getMessage(), nfe); return Util.badRequestResponse(errMap, nfe.getMessage()); } try { result = ds.updateObject("user", new SMString(user), update); feedback.put("Updated object", result); } catch (InvalidSchemaException ise) { return Util.internalErrorResponse("invalid_schema", ise, errMap); // http 500 - internal server error } catch (DatastoreException dse) { return Util.internalErrorResponse("datastore_exception", dse, errMap); // http 500 - internal server error } return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback); }
From source file:com.letsgood.synergykitsdkandroid.requestmethods.Delete.java
@Override public BufferedReader execute() { String uri = null;/*from w ww . j a v a 2 s .co m*/ //init check if (!Synergykit.isInit()) { SynergykitLog.print(Errors.MSG_SK_NOT_INITIALIZED); statusCode = Errors.SC_SK_NOT_INITIALIZED; return null; } //URI check uri = getUri().toString(); if (uri == null) { statusCode = Errors.SC_URI_NOT_VALID; return null; } //session token check if (sessionTokenRequired && sessionToken == null) { statusCode = Errors.SC_NO_SESSION_TOKEN; return null; } try { url = new URL(uri); // init url httpURLConnection = (HttpURLConnection) url.openConnection(); //open connection httpURLConnection.setConnectTimeout(CONNECT_TIMEOUT); //set connect timeout httpURLConnection.setReadTimeout(READ_TIMEOUT); //set read timeout httpURLConnection.setRequestMethod(REQUEST_METHOD); //set method httpURLConnection.addRequestProperty(PROPERTY_USER_AGENT, PROPERTY_USER_AGENT_VALUE); //set property httpURLConnection.addRequestProperty(PROPERTY_CONTENT_TYPE, ACCEPT_APPLICATION_VALUE); httpURLConnection.addRequestProperty(PROPERTY_AUTHORIZATION, "Basic " + Base64.encodeToString( (Synergykit.getTenant() + ":" + Synergykit.getApplicationKey()).getBytes(), Base64.NO_WRAP)); //set authorization if (Synergykit.getSessionToken() != null) httpURLConnection.addRequestProperty(PROPERTY_SESSION_TOKEN, Synergykit.getSessionToken()); statusCode = httpURLConnection.getResponseCode(); //get status code //read stream if (statusCode >= HttpURLConnection.HTTP_OK && statusCode < HttpURLConnection.HTTP_MULT_CHOICE) { return null; } else { return readStream(httpURLConnection.getErrorStream()); } } catch (Exception e) { statusCode = HttpStatus.SC_SERVICE_UNAVAILABLE; e.printStackTrace(); return null; } }
From source file:com.stackmob.example.CRUD.UpdateObject.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { String carID = ""; String year = ""; LoggerService logger = serviceProvider.getLoggerService(UpdateObject.class); logger.debug(request.getBody());/*from ww w . j av a 2 s . c o m*/ Map<String, String> errMap = new HashMap<String, String>(); /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations * from the JSON request body */ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; // Fetch the values passed in by the user from the body of JSON carID = (String) jsonObject.get("car_ID"); year = (String) jsonObject.get("year"); } catch (ParseException pe) { logger.error(pe.getMessage(), pe); return Util.badRequestResponse(errMap, pe.getMessage()); } if (Util.hasNulls(year, carID)) { return Util.badRequestResponse(errMap); } Map<String, SMValue> feedback = new HashMap<String, SMValue>(); feedback.put("updated year", new SMInt(Long.parseLong(year))); DataService ds = serviceProvider.getDataService(); List<SMUpdate> update = new ArrayList<SMUpdate>(); /* Create the changes in the form of an Update that you'd like to apply to the object * In this case I want to make changes to year by overriding existing values with user input */ update.add(new SMSet("year", new SMInt(Long.parseLong(year)))); SMObject result; try { // Remember that the primary key in this car schema is `car_id` result = ds.updateObject("car", new SMString(carID), update); feedback.put("updated object", result); } catch (InvalidSchemaException ise) { return Util.internalErrorResponse("invalid_schema", ise, errMap); // http 500 - internal server error } catch (DatastoreException dse) { return Util.internalErrorResponse("datastore_exception", dse, errMap); // http 500 - internal server error } return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback); }
From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java
/** send a POST request and return the response as string */ String sendPostRequest(String url, String bodytext) throws Exception { String sresponse;//from www .j a v a2 s . c om HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); // add authorization header httppost.addHeader("Authorization", authHeader); StringEntity body = new StringEntity(bodytext); httppost.setEntity(body); HttpResponse response = httpclient.execute(httppost); // check statuscode if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED) { HttpEntity entity = response.getEntity(); sresponse = readResponseStream(entity.getContent()); httpclient.getConnectionManager().shutdown(); } else { HttpEntity entity = response.getEntity(); sresponse = readResponseStream(entity.getContent()); String httpcode = Integer.toString(response.getStatusLine().getStatusCode()); httpclient.getConnectionManager().shutdown(); throw new ReferenceSystemException(httpcode, "Bibsonomy Error", XMLUtils.parseError(sresponse)); } return sresponse; }
From source file:edu.usf.cutr.opentripplanner.android.pois.GooglePlaces.java
public JSONObject requestPlaces(String paramLocation, String paramRadius, String paramName) { StringBuilder builder = new StringBuilder(); String encodedParamLocation = ""; String encodedParamRadius = ""; String encodedParamName;/*from w w w . j a v a 2s. c o m*/ try { if ((paramLocation != null) && (paramRadius != null)) { encodedParamLocation = URLEncoder.encode(paramLocation, OTPApp.URL_ENCODING); encodedParamRadius = URLEncoder.encode(paramRadius, OTPApp.URL_ENCODING); } encodedParamName = URLEncoder.encode(paramName, OTPApp.URL_ENCODING); } catch (UnsupportedEncodingException e1) { Log.e(OTPApp.TAG, "Error encoding Google Places request"); e1.printStackTrace(); return null; } if ((paramLocation != null) && (paramRadius != null)) { request += "location=" + encodedParamLocation; request += "&radius=" + encodedParamRadius; request += "&query=" + encodedParamName; } else { request += "query=" + encodedParamName; } request += "&sensor=false"; request += "&key=" + getApiKey(); Log.d(OTPApp.TAG, request); HttpURLConnection urlConnection = null; try { URL url = new URL(request); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(OTPApp.HTTP_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(OTPApp.HTTP_SOCKET_TIMEOUT); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.e(OTPApp.TAG, "Error obtaining Google Places response, status code: \" + status"); } } catch (IOException e) { Log.e(OTPApp.TAG, "Error obtaining Google Places response" + e.toString()); e.printStackTrace(); return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } } Log.d(OTPApp.TAG, builder.toString()); JSONObject json = null; try { json = new JSONObject(builder.toString()); } catch (JSONException e) { Log.e(OTPApp.TAG, "Error parsing Google Places data " + e.toString()); } return json; }
From source file:com.qubole.rubix.hadoop2.hadoop2CM.Hadoop2ClusterManager.java
@Override public void initialize(Configuration conf) { super.initialize(conf); yconf = new YarnConfiguration(); this.address = yconf.get(addressConf, address); this.serverAddress = address.substring(0, address.indexOf(":")); this.serverPort = Integer.parseInt(address.substring(address.indexOf(":") + 1)); ExecutorService executor = Executors.newSingleThreadExecutor(); nodesCache = CacheBuilder.newBuilder().refreshAfterWrite(getNodeRefreshTime(), TimeUnit.SECONDS) .build(CacheLoader.asyncReloading(new CacheLoader<String, List<String>>() { @Override//from w w w . j a v a 2 s. c om public List<String> load(String s) throws Exception { if (!isMaster) { // First time all nodes start assuming themselves as master and down the line figure out their role // Next time onwards, only master will be fetching the list of nodes return ImmutableList.of(); } try { StringBuffer response = new StringBuffer(); URL obj = getNodeURL(); HttpURLConnection httpcon = (HttpURLConnection) obj.openConnection(); httpcon.setRequestMethod("GET"); log.debug("Sending 'GET' request to URL: " + obj.toString()); int responseCode = httpcon.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader( new InputStreamReader(httpcon.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); httpcon.disconnect(); } else { log.info("/ws/v1/cluster/nodes failed due to " + responseCode + ". Setting this node as worker."); isMaster = false; httpcon.disconnect(); return ImmutableList.of(); } Gson gson = new Gson(); Type type = new TypeToken<Nodes>() { }.getType(); Nodes nodes = gson.fromJson(response.toString(), type); List<Elements> allNodes = nodes.getNodes().getNode(); Set<String> hosts = new HashSet<>(); for (Elements node : allNodes) { String state = node.getState(); log.debug("Hostname: " + node.getNodeHostName() + "State: " + state); //keep only healthy data nodes if (state.equalsIgnoreCase("Running") || state.equalsIgnoreCase("New") || state.equalsIgnoreCase("Rebooted")) { hosts.add(node.getNodeHostName()); } } if (hosts.isEmpty()) { throw new Exception("No healthy data nodes found."); } List<String> hostList = Lists.newArrayList(hosts.toArray(new String[0])); Collections.sort(hostList); log.debug("Hostlist: " + hostList.toString()); return hostList; } catch (Exception e) { throw Throwables.propagate(e); } } }, executor)); }
From source file:com.baseproject.volley.toolbox.HttpClientStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest);// www . j av a 2 s. c om HttpParams httpParams = httpRequest.getParams(); //int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, request.getReadTimeoutMs()); HttpResponse httpResponse = mClient.execute(httpRequest); if (httpResponse != null && httpResponse.getStatusLine() != null) { int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_NOT_MODIFIED && statusCode != HttpURLConnection.HTTP_OK) { throw new IOException(Util.buildHttpErrorMsg("failed", statusCode, "unknown")); } } return httpResponse; }
From source file:org.fedoraproject.copr.client.impl.RpcCommand.java
public T execute(DefaultCoprSession session) throws CoprException { try {/*from ww w . j ava2 s . c o m*/ HttpClient client = session.getClient(); String baseUrl = session.getConfiguration().getUrl(); String commandUrl = getCommandUrl(); String url = baseUrl + commandUrl; Map<String, String> extraArgs = getExtraArguments(); HttpUriRequest request; if (extraArgs == null) { request = new HttpGet(url); } else { HttpPost post = new HttpPost(url); request = post; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); for (Entry<String, String> entry : extraArgs.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } if (requiresAuthentication()) { String login = session.getConfiguration().getLogin(); if (login == null || login.isEmpty()) throw new CoprException("Authentification is required to perform this command " + "but no login was provided in configuration"); String token = session.getConfiguration().getToken(); if (token == null || token.isEmpty()) throw new CoprException("Authentification is required to perform this command " + "but no login was provided in configuration"); String auth = login + ":" + token; String encodedAuth = DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.UTF_8)); request.setHeader("Authorization", "Basic " + encodedAuth); } request.addHeader("Accept", APPLICATION_JSON.getMimeType()); HttpResponse response = client.execute(request); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new CoprException( "Copr RPC failed: HTTP " + returnCode + " " + response.getStatusLine().getReasonPhrase()); } Reader responseReader = new InputStreamReader(response.getEntity().getContent()); JsonParser parser = new JsonParser(); JsonObject rpcResponse = parser.parse(responseReader).getAsJsonObject(); String rpcStatus = rpcResponse.get("output").getAsString(); if (!rpcStatus.equals("ok")) { throw new CoprException("Copr RPC returned failure reponse"); } return parseResponse(rpcResponse); } catch (IOException e) { throw new CoprException("Failed to call remote Copr procedure", e); } }
From source file:jfix.util.Urls.java
/** * Returns true if given url can be connected via HTTP within given timeout * (specified in seconds). Otherwise the url might be broken. */// w w w . ja va2 s. c o m public static boolean isConnectable(String url, int timeout) { try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setConnectTimeout(timeout * 1000); httpConnection.setReadTimeout(timeout * 1000); httpConnection.connect(); int response = httpConnection.getResponseCode(); httpConnection.disconnect(); return response == HttpURLConnection.HTTP_OK; } } catch (Exception e) { return false; } return false; }
From source file:org.openremote.android.test.console.net.ORNetworkCheckTest.java
/** * Connect to controller.openremote.org/test/controller and attempt to verify the existence * of "SimpleName" panel design./*from www. jav a2s . c o m*/ * * @throws IOException if connecting to remote controller fails for every reason */ public void testVerifyControllerURL() throws IOException { try { AppSettingsModel.setCurrentPanelIdentity(ctx, "SimpleName"); if (!wifi.isWifiEnabled()) fail(wifiRequired()); HttpResponse response = ORNetworkCheck.verifyControllerURL(ctx, "http://controller.openremote.org/test/controller"); assertNotNull("Got null HTTP response, was expecting: " + HttpURLConnection.HTTP_OK, response); int status = response.getStatusLine().getStatusCode(); assertTrue("Was expecting HTTP_OK, got " + status, status == HttpURLConnection.HTTP_OK); } finally { AppSettingsModel.setCurrentPanelIdentity(ctx, null); } }