List of usage examples for java.net HttpURLConnection HTTP_NO_CONTENT
int HTTP_NO_CONTENT
To view the source code for java.net HttpURLConnection HTTP_NO_CONTENT.
Click Source Link
From source file:org.openbaton.sdk.api.util.RestRequest.java
public Serializable requestPost(final String id, final Serializable object) throws SDKException { CloseableHttpResponse response = null; HttpPost httpPost = null;/*from ww w . jav a 2 s .co m*/ try { log.trace("Object is: " + object); String fileJSONNode; if (object instanceof String) fileJSONNode = (String) object; else fileJSONNode = mapper.toJson(object); log.trace("sending: " + fileJSONNode.toString()); log.debug("baseUrl: " + baseUrl); log.debug("id: " + baseUrl + "/" + id); try { checkToken(); } catch (IOException e) { log.error(e.getMessage(), e); throw new SDKException("Could not get token", e); } // call the api here log.debug("Executing post on: " + this.baseUrl + "/" + id); httpPost = new HttpPost(this.baseUrl + "/" + id); if (!(object instanceof String)) { httpPost.setHeader(new BasicHeader("accept", "application/json")); httpPost.setHeader(new BasicHeader("Content-Type", "application/json")); } httpPost.setHeader(new BasicHeader("project-id", projectId)); if (token != null) httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", ""))); httpPost.setEntity(new StringEntity(fileJSONNode)); response = httpClient.execute(httpPost); // check response status checkStatus(response, HttpURLConnection.HTTP_CREATED); // return the response of the request String result = ""; if (response.getEntity() != null) result = EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_NO_CONTENT) { if (object instanceof String) return result; JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result); result = mapper.toJson(jsonElement); log.trace("received: " + result); log.trace("Casting it into: " + object.getClass()); return mapper.fromJson(result, object.getClass()); } response.close(); httpPost.releaseConnection(); return null; } catch (IOException e) { // catch request exceptions here log.error(e.getMessage(), e); if (httpPost != null) httpPost.releaseConnection(); throw new SDKException("Could not http-post or open the object properly", e); } catch (SDKException e) { if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { token = null; if (httpPost != null) httpPost.releaseConnection(); return requestPost(id); } else if (response != null) { if (httpPost != null) httpPost.releaseConnection(); throw new SDKException("Status is " + response.getStatusLine().getStatusCode()); } else { throw e; } } }
From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java
@Test public void testPutNode() throws IOException, JSONException { List<String> locations = getTestPreferenceNodes(); for (String location : locations) { //put a node that isn't currently defined JSONObject prefs = new JSONObject(); prefs.put("Name", "Frodo"); prefs.put("Address", "Bag End"); WebRequest request = new PutMethodWebRequest(location, IOUtilities.toInputStream(prefs.toString()), "application/json"); setAuthentication(request);// ww w . ja va 2s .c o m WebResponse response = webConversation.getResource(request); assertEquals("1." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); //doing a get should succeed request = new GetMethodWebRequest(location + "?key=Address"); setAuthentication(request); response = webConversation.getResource(request); assertEquals("2." + location, HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject result = new JSONObject(response.getText()); assertEquals("3." + location, "Bag End", result.optString("Address")); //setting a node with disjoint values should clear values not in common prefs = new JSONObject(); prefs.put("Name", "Barliman"); prefs.put("Occupation", "Barkeep"); request = new PutMethodWebRequest(location, IOUtilities.toInputStream(prefs.toString()), "application/json"); setAuthentication(request); response = webConversation.getResource(request); assertEquals("4." + location, HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); request = new GetMethodWebRequest(location); setAuthentication(request); response = webConversation.getResource(request); assertEquals("5." + location, HttpURLConnection.HTTP_OK, response.getResponseCode()); result = new JSONObject(response.getText()); assertEquals("6." + location, "Barliman", result.optString("Name")); assertFalse("7." + location, result.has("Address"));//this value was previously defined but the put node should clean it assertEquals("8." + location, "Barkeep", result.optString("Occupation")); } }
From source file:com.vuzix.samplewebrtc.android.SessionChannel.java
public void send(final Peer peer, final JSONObject message) { mSendHandler.post(new Runnable() { @Override//from w ww.ja v a 2 s. c om public void run() { if (peer.mDisconnected) { return; } HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) new URL(peer.mPeerUrl).openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream os = urlConnection.getOutputStream(); os.write(message.toString().getBytes("UTF-8")); os.flush(); os.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) { Log.e(TAG, "response " + responseCode); } } catch (IOException e) { Log.e(TAG, "IOException", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } } }); }
From source file:com.vmware.admiral.compute.RegistryHostConfigService.java
private void completeOperationSuccess(Operation op) { op.setStatusCode(HttpURLConnection.HTTP_NO_CONTENT); op.setBody(null); op.complete(); }
From source file:com.ontotext.s4.client.HttpClient.java
/** * Read a response or error message from the given connection, handling any 303 redirect responses * if <code>followRedirects</code> is true. *///from w w w . j av a 2 s. c o m private <T> T readResponseOrError(HttpURLConnection connection, TypeReference<T> responseType, boolean followRedirects) throws HttpClientException { InputStream stream = null; try { int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) { // successful response with no content return null; } String encoding = connection.getContentEncoding(); if ("gzip".equalsIgnoreCase(encoding)) { stream = new GZIPInputStream(connection.getInputStream()); } else { stream = connection.getInputStream(); } if (responseCode < 300 || responseCode >= 400 || !followRedirects) { try { return MAPPER.readValue(stream, responseType); } finally { stream.close(); } } else { // redirect - all redirects we care about from the S4 // APIs are 303. We have to follow them manually to make // authentication work properly. String location = connection.getHeaderField("Location"); // consume body IOUtils.copy(stream, new NullOutputStream()); IOUtils.closeQuietly(stream); // follow the redirect return get(location, responseType); } } catch (Exception e) { readError(connection); return null; // unreachable, as readError always throws exception } }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;//from ww w .ja v a2 s . c o m BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:com.vmware.admiral.test.integration.BaseIntegrationSupportIT.java
protected static ComputeState addHost(ComputeState computeState) throws Exception { if (computeState.id != null) { String documentSelfLink = buildServiceUri(ComputeService.FACTORY_LINK, computeState.id); String body = sendRequest(HttpMethod.GET, documentSelfLink, null); if (body != null && !body.isEmpty()) { delete(documentSelfLink);//from w w w.j av a 2 s . c o m } } ContainerHostSpec hostSpec = new ContainerHostSpec(); hostSpec.hostState = computeState; hostSpec.acceptCertificate = true; HttpResponse httpResponse = SimpleHttpsClient.execute(HttpMethod.PUT, getBaseUrl() + buildServiceUri(ContainerHostService.SELF_LINK), Utils.toJson(hostSpec)); if (HttpURLConnection.HTTP_NO_CONTENT != httpResponse.statusCode) { throw new IllegalArgumentException("Add host failed with status code: " + httpResponse.statusCode); } List<String> headers = httpResponse.headers.get(Operation.LOCATION_HEADER); String computeStateLink = headers.get(0); waitForStateChange(computeStateLink, t -> { ComputeStateWithDescription host = Utils.fromJson(t, ComputeStateWithDescription.class); return host.powerState.equals(PowerState.ON); }); return getDocument(computeStateLink, ComputeState.class); }
From source file:org.eclipse.orion.server.tests.prefs.PreferenceTest.java
@Test public void testValueWithSpaces() throws IOException, JSONException { //put a value String location = getTestPreferenceNodes().get(0); WebRequest request = createSetPreferenceRequest(location, "Name", "Frodo Baggins"); setAuthentication(request);/*from w ww .jav a 2 s.com*/ WebResponse response = webConversation.getResource(request); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); //now doing a get should succeed request = new GetMethodWebRequest(location + "?key=Name"); setAuthentication(request); response = webConversation.getResource(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject result = new JSONObject(response.getText()); assertEquals("Frodo Baggins", result.optString("Name")); }
From source file:bluevia.InitService.java
void doPolling() { Thread threadPoller = ThreadManager.createBackgroundThread(new Runnable() { public void run() { String consumer_key = Util.BlueViaOAuth.consumer_key; String consumer_secret = Util.BlueViaOAuth.consumer_secret; BufferedReader br = null; int countryIndex = 0; String[] countryURIs = { MO_URI_UK, MO_URI_SP, MO_URI_GE, MO_URI_BR, MO_URI_MX, MO_URI_AR, MO_URI_CH, MO_URI_CO }; while (true) { try { com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate(); OAuthConsumer consumer = (OAuthConsumer) new DefaultOAuthConsumer(consumer_key, consumer_secret); consumer.setMessageSigner(new HmacSha1MessageSigner()); URL apiURI = new URL(countryURIs[countryIndex]); countryIndex = (countryIndex + 1) % countryURIs.length; int rc = 0; HttpURLConnection request = (HttpURLConnection) apiURI.openConnection(); request.setRequestMethod("GET"); consumer.sign(request); rc = request.getResponseCode(); if (rc == HttpURLConnection.HTTP_OK) { br = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuffer doc = new StringBuffer(); String line; do { line = br.readLine(); if (line != null) doc.append(line); } while (line != null); DatastoreService datastore = Util.getDatastoreServiceInstance(); Transaction txn = datastore.beginTransaction(); try { JSONObject apiResponse; JSONObject smsPool; JSONArray smsInfo; apiResponse = new JSONObject(doc.toString()); if (apiResponse.getString("receivedSMS") != null) { String szMessage; String szOrigin; String szDate; smsPool = apiResponse.getJSONObject("receivedSMS"); smsInfo = smsPool.optJSONArray("receivedSMS"); if (smsInfo != null) { for (int i = 0; i < smsInfo.length(); i++) { szMessage = smsInfo.getJSONObject(i).getString("message"); szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress") .getString("phoneNumber"); szDate = smsInfo.getJSONObject(i).getString("dateTime"); StringTokenizer msgParser = new StringTokenizer(szMessage); // Removing app id msgParser.nextToken(); String userAlias = msgParser.nextToken(); String msg = ""; while (msgParser.hasMoreTokens()) msg += " " + msgParser.nextToken(); String userEmail = (String) Util.getUserWithAlias(userAlias) .getProperty("mail"); if (userEmail != null) { Util.addUserMessage(userEmail, szOrigin, msg, szDate); SendSMS.setTwitterStatus(userEmail, msg); SendSMS.setFacebookWallPost(userEmail, msg); } }//www . j a v a 2 s. c o m } else { JSONObject sms = smsPool.getJSONObject("receivedSMS"); szMessage = sms.getString("message"); szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber"); szDate = sms.getString("dateTime"); StringTokenizer msgParser = new StringTokenizer(szMessage); // Removing app id msgParser.nextToken(); String userAlias = msgParser.nextToken(); String msg = ""; while (msgParser.hasMoreTokens()) msg += " " + msgParser.nextToken(); Util.addUserMessage(userAlias, szOrigin, msg, szDate); } } else { logger.warning("No messages"); if (txn.isActive()) txn.rollback(); } } catch (JSONException e) { logger.severe(e.getMessage()); } catch (Exception e) { logger.severe(e.getMessage()); } finally { if (txn.isActive()) txn.rollback(); } } else if (rc == HttpURLConnection.HTTP_NO_CONTENT) { //log.warning(String.format("No content from: %s", apiURI.getPath())); } else logger.severe(String.format("%d: %s", rc, request.getResponseMessage())); } catch (Exception e) { logger.severe(e.getMessage()); } Thread.currentThread(); try { Thread.sleep(150000); } catch (InterruptedException e) { e.printStackTrace(); logger.severe(String.format("%s", e.getMessage())); } } } }); threadPoller.start(); }