List of usage examples for java.net HttpURLConnection HTTP_CREATED
int HTTP_CREATED
To view the source code for java.net HttpURLConnection HTTP_CREATED.
Click Source Link
From source file:typicalnerd.musicarchive.client.network.FileUploader.java
/** * Upload a file's meta data to the web service. * /*from w w w . j av a 2 s . c om*/ * @param metaData * The meta data of the file. * * @param uploadResult * The result of the file upload. This contains the location where to POST the meta * data. * * @return * Returns the {@link MetaUploadResult} in case of a successful upload. * * @throws IOException */ private MetaUploadResult uploadMeta(TrackMetaData metaData, FileUploadResult uploadResult) throws IOException { // This time we need to turn things around and prepare the data first. Only then // can we specify the "Content-Length" header of the request. It is not necessary // per se, but it makes us a good citizen if we can tell the server how big the // data will be. In theory this would allow to calculate an ETA and other stats // that are not very relevant for this small data. String json = mapper.writeValueAsString(metaData); byte[] binary = json.getBytes(StandardCharsets.UTF_8); // Now we can do the URL setup dance. URL url = new URL(baseUrl + uploadResult.getMetaUrl()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(json.length())); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setDoInput(true); try (ByteArrayInputStream in = new ByteArrayInputStream(binary)) { try (OutputStream out = connection.getOutputStream()) { // Still lazy ;-) IOUtils.copy(in, out); } } connection.connect(); int result = connection.getResponseCode(); if (HttpURLConnection.HTTP_CREATED != result) { try (InputStream in = connection.getInputStream()) { ErrorResponse e = mapper.readValue(in, ErrorResponse.class); throw new UnknownServiceException("Upload of meta data failed. " + e.getMessage()); } } // Fanfare! We're done. return new MetaUploadResult(result); }
From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java
public static String put(URL url, InputStream inputStream, String contentType, String encoding) throws OseeCoreException { int statusCode = -1; String response = null;/*from ww w .j a v a2 s. c om*/ PutMethod method = new PutMethod(url.toString()); InputStream responseInputStream = null; AcquireResult result = new AcquireResult(); try { method.setRequestHeader(CONTENT_ENCODING, encoding); method.setRequestEntity(new InputStreamRequestEntity(inputStream, contentType)); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); statusCode = executeMethod(url, method); responseInputStream = method.getResponseBodyAsStream(); result.setContentType(getContentType(method)); result.setEncoding(method.getResponseCharSet()); if (statusCode != HttpURLConnection.HTTP_CREATED) { String exceptionString = Lib.inputStreamToString(responseInputStream); throw new OseeCoreException(exceptionString); } else { responseInputStream = method.getResponseBodyAsStream(); response = Lib.inputStreamToString(responseInputStream); } } catch (Exception ex) { OseeExceptions.wrapAndThrow(ex); } finally { Lib.close(responseInputStream); method.releaseConnection(); } return response; }
From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java
protected void finishPutTransfer(Resource resource, InputStream input, OutputStream output) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { try {//from ww w . j a v a 2 s . co m int statusCode = putConnection.getResponseCode(); switch (statusCode) { // Success Codes case HttpURLConnection.HTTP_OK: // 200 case HttpURLConnection.HTTP_CREATED: // 201 case HttpURLConnection.HTTP_ACCEPTED: // 202 case HttpURLConnection.HTTP_NO_CONTENT: // 204 break; case HttpURLConnection.HTTP_FORBIDDEN: throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName())); case HttpURLConnection.HTTP_NOT_FOUND: throw new ResourceDoesNotExistException( "File: " + buildUrl(resource.getName()) + " does not exist"); // add more entries here default: throw new TransferFailedException("Failed to transfer file: " + buildUrl(resource.getName()) + ". Return code is: " + statusCode); } } catch (IOException e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException("Error transferring file: " + e.getMessage(), e); } }
From source file:org.eclipse.orion.server.tests.servlets.files.AdvancedFilesTest.java
@Test public void testMetadataHandling() throws JSONException, IOException, SAXException { String fileName = "testMetadataHandling.txt"; //setup: create a file WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); //obtain file metadata and ensure data is correct request = getGetFilesRequest(fileName + "?parts=meta"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject responseObject = new JSONObject(response.getText()); assertNotNull("No file information in response", responseObject); checkFileMetadata(responseObject, fileName, new Long(-1), null, null, request.getURL().getRef(), new Long(0), null, null, null); //modify the metadata request = getPutFileRequest(fileName + "?parts=meta", getFileMetadataObject(true, true).toString()); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); //fetch the metadata again and ensure it is changed request = getGetFilesRequest(fileName + "?parts=meta"); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); responseObject = new JSONObject(response.getText()); checkFileMetadata(responseObject, fileName, new Long(-1), null, null, request.getURL().getRef(), new Long(0), new Boolean(true), new Boolean(true), null); //make the file writeable again so test can clean up request = getPutFileRequest(fileName + "?parts=meta", getFileMetadataObject(false, false).toString()); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); }
From source file:com.tc.rest.client.JsonClient.java
@Override public String delete(String json, String strurl) { StringBuilder builder = new StringBuilder(); OutputStream os = null;//from ww w.j av a2s . c o m HttpURLConnection conn = null; try { URL url = new URL(strurl); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("delete"); conn.setRequestProperty("Content-Type", "application/json"); if (this.useCreds) { this.applyCredentials(conn); } String input = json; os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.log(Level.INFO, "Output from Server .... \n"); while ((output = br.readLine()) != null) { builder.append(output); } conn.disconnect(); } catch (Exception e) { logger.log(Level.SEVERE, null, e); } finally { conn.disconnect(); IOUtils.closeQuietly(os); } return builder.toString(); }
From source file:com.murrayc.galaxyzoo.app.provider.test.ZooniverseClientTest.java
public void testUploadWithSuccess() throws IOException, InterruptedException, ZooniverseClient.UploadException { final MockWebServer server = new MockWebServer(); final MockResponse response = new MockResponse(); response.setResponseCode(HttpURLConnection.HTTP_CREATED); response.setBody("TODO"); server.enqueue(response);/*ww w . j a v a2 s. co m*/ server.play(); final ZooniverseClient client = createZooniverseClient(server); //SyncAdapter.doUploadSync() adds an "interface" parameter too, //but we are testing a more generic API here: final List<NameValuePair> values = new ArrayList<>(); values.add(new BasicNameValuePair("classification[subject_ids][]", "504e4a38c499611ea6010c6a")); values.add(new BasicNameValuePair("classification[favorite][]", "true")); values.add(new BasicNameValuePair("classification[annotations][0][sloan-0]", "a-0")); values.add(new BasicNameValuePair("classification[annotations][1][sloan-7]", "a-1")); values.add(new BasicNameValuePair("classification[annotations][2][sloan-5]", "a-0")); values.add(new BasicNameValuePair("classification[annotations][3][sloan-6]", "x-5")); final boolean result = client.uploadClassificationSync("testAuthName", "testAuthApiKey", values); assertTrue(result); assertEquals(1, server.getRequestCount()); //This is really just a regression test, //so we notice if something changes unexpectedly: final RecordedRequest request = server.takeRequest(); assertEquals("POST", request.getMethod()); assertEquals("/workflows/50251c3b516bcb6ecb000002/classifications", request.getPath()); assertNotNull(request.getHeader("Authorization")); assertEquals("application/x-www-form-urlencoded", request.getHeader("Content-Type")); final byte[] contents = request.getBody(); final String strContents = new String(contents, Utils.STRING_ENCODING); assertEquals( "classification%5Bsubject_ids%5D%5B%5D=504e4a38c499611ea6010c6a&classification%5Bfavorite%5D%5B%5D=true&classification%5Bannotations%5D%5B0%5D%5Bsloan-0%5D=a-0&classification%5Bannotations%5D%5B1%5D%5Bsloan-7%5D=a-1&classification%5Bannotations%5D%5B2%5D%5Bsloan-5%5D=a-0&classification%5Bannotations%5D%5B3%5D%5Bsloan-6%5D=x-5", strContents); server.shutdown(); }
From source file:org.cm.podd.report.util.RequestDataUtil.java
public static ResponseObject registerDeviceId(String deviceId, String token) { JSONObject jsonObj = null;//from ww w. ja v a 2 s .c o m int statusCode = 0; //SharedPreferences settings = PoddApplication.getAppContext().getSharedPreferences("PoddPrefsFile", 0); String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL); String reqUrl = serverUrl + "/gcm/"; Log.i(TAG, "submit url=" + reqUrl); HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient client = new DefaultHttpClient(params); try { HttpPost post = new HttpPost(reqUrl); post.setHeader("Content-Type", "application/json"); if (token != null) { post.setHeader("Authorization", "Token " + token); } JSONObject data = new JSONObject(); try { data.put("gcmRegId", deviceId); } catch (JSONException e) { Log.e(TAG, "Error while create json object", e); } post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8)); HttpResponse response; response = client.execute(post); HttpEntity entity = response.getEntity(); // Detect server complaints statusCode = response.getStatusLine().getStatusCode(); Log.v(TAG, "status code=" + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { InputStream in = entity.getContent(); String resp = FileUtil.convertInputStreamToString(in); Log.d(TAG, "Register device id : Response text= " + resp); jsonObj = new JSONObject(); entity.consumeContent(); } } catch (ClientProtocolException e) { Log.e(TAG, "error post data", e); } catch (IOException e) { Log.e(TAG, "Can't connect server", e); } finally { client.getConnectionManager().shutdown(); } return new ResponseObject(statusCode, jsonObj); }
From source file:com.flurry.proguard.UploadProGuardMapping.java
/** * Register this upload with the metadata service * * @param projectId the id of the project * @param payload the JSON body to send/*from w w w. j a v a 2s .c om*/ * @param token the Flurry auth token * @return the id of the created upload */ private static String createUpload(String projectId, String payload, String token) { String postUrl = String.format("%s/project/%s/uploads", METADATA_BASE, projectId); List<Header> requestHeaders = getMetadataHeaders(token); HttpPost postRequest = new HttpPost(postUrl); postRequest.setEntity(new StringEntity(payload, Charset.forName("UTF-8"))); HttpResponse response = executeHttpRequest(postRequest, requestHeaders); expectStatus(response, HttpURLConnection.HTTP_CREATED); JSONObject jsonObject = getJsonFromEntity(response.getEntity()); return jsonObject.getJSONObject("data").get("id").toString(); }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public boolean upload(String sessionId, File file, List<String> includes, List<String> excludes, String dataspacePath, final String path) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath).append('/') .append(escapeUrlPathSegment(path)); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();/* w w w.j a v a2 s . c o m*/ ResteasyWebTarget target = client.target(uriTmpl.toString()); Response response = null; try { response = target.request().header("sessionid", sessionId) .put(Entity.entity(new CompressedStreamingOutput(file, includes, excludes), new Variant(MediaType.APPLICATION_OCTET_STREAM_TYPE, (Locale) null, encoding(file)))); if (response.getStatus() != HttpURLConnection.HTTP_CREATED) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("File upload failed. Status code: %d", response.getStatus()), response); } } return true; } finally { if (response != null) { response.close(); } } }
From source file:uk.co.firstzero.webdav.Push.java
/** * Uploads the file. The File object (f) is used for creating a FileInputStream for uploading * files to webdav// w ww .j av a 2 s .c o m * @param f The File object of the file to be uploaded * @param filename The relatvie path of the file */ public boolean uploadFile(File f, String filename) throws IOException { String uploadUrl = url + "/" + filename; boolean uploaded = false; deleteFile(uploadUrl); PutMethod putMethod = new PutMethod(uploadUrl); logger.debug("Check if file exists - " + fileExists(uploadUrl)); if (!fileExists(uploadUrl)) { RequestEntity requestEntity = new InputStreamRequestEntity(new FileInputStream(f)); putMethod.setRequestEntity(requestEntity); httpClient.executeMethod(putMethod); logger.trace("uploadFile - statusCode - " + putMethod.getStatusCode()); switch (putMethod.getStatusCode()) { case HttpURLConnection.HTTP_NO_CONTENT: logger.info("IGNORE - File already exists " + f.getAbsolutePath()); break; case HttpURLConnection.HTTP_OK: uploaded = true; logger.info("Transferred " + f.getAbsolutePath()); break; case HttpURLConnection.HTTP_CREATED: //201 Created => No issues uploaded = true; logger.info("Transferred " + f.getAbsolutePath()); break; default: logger.error("ERR " + " " + putMethod.getStatusCode() + " " + putMethod.getStatusText() + " " + f.getAbsolutePath()); break; } } else { logger.info("IGNORE - File already exists " + f.getAbsolutePath()); } return uploaded; }