List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.wso2.msf4j.internal.router.HttpServerTest.java
@Test public void testGzipCompressionWithGzipAccept() throws Exception { HttpURLConnection urlConn = request("/test/v1/gzipfile", HttpMethod.GET); urlConn.addRequestProperty(HttpHeaders.Names.ACCEPT_ENCODING, "gzip"); Assert.assertEquals(HttpResponseStatus.OK.code(), urlConn.getResponseCode()); String contentEncoding = urlConn.getHeaderField(HttpHeaders.Names.CONTENT_ENCODING); Assert.assertTrue("gzip".equalsIgnoreCase(contentEncoding)); InputStream downStream = urlConn.getInputStream(); Assert.assertTrue(IOUtils.toByteArray(downStream).length < IOUtils .toByteArray(Resources.getResource("testJpgFile.jpg").openStream()).length); }
From source file:org.wso2.msf4j.internal.router.HttpServerTest.java
@Test public void testHeaderResponse() throws IOException { HttpURLConnection urlConn = request("/test/v1/headerResponse", HttpMethod.GET); urlConn.addRequestProperty("name", "name1"); Assert.assertEquals(200, urlConn.getResponseCode()); Assert.assertEquals("name1", urlConn.getHeaderField("name")); urlConn.disconnect();// www .java 2 s.c o m }
From source file:org.cohorte.ecf.provider.jabsorb.host.JabsorbHttpSession.java
/** * Sends a POST request to the session URL with the given content * /*w ww . ja v a 2 s . co m*/ * @param aRequestContent * Request content * @return The result page * @throws ClientError * Something wrong happened */ protected String getUrlPostResult(final byte[] aRequestContent) { // Open a connection HttpURLConnection httpConnection = null; Scanner scanner = null; try { // Open the connection and cast it final URLConnection connection = pUrl.openConnection(); if (!(connection instanceof HttpURLConnection)) { throw new ClientError("Unknown URL connection for : " + pUrl); } httpConnection = (HttpURLConnection) connection; // Make the connection writable (POST) httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); // Set up the headers httpConnection.addRequestProperty("Content-Type", JSON_CONTENT_TYPE); httpConnection.addRequestProperty("Content-Length", Integer.toString(aRequestContent.length)); // Set POST data httpConnection.getOutputStream().write(aRequestContent); // Wait for an answer final int responseCode = httpConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new ClientError("Got HTTP Status " + responseCode + " for URL " + pUrl); } // Use a scanner to read the response content See here for more // information: // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\A"); return scanner.next(); } catch (final IOException e) { // Convert error class throw new ClientError(e); } finally { // In any case, free the connection if (httpConnection != null) { httpConnection.disconnect(); } // ... and close the scanner if (scanner != null) { scanner.close(); } } }
From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java
/** * Talks to the http interface to create a file. * * @param filename The file to create//from w ww . ja v a2s . c o m * @param perms The permission field, if any (may be null) * @throws Exception */ private void createWithHttp(String filename, String perms) throws Exception { String user = HadoopUsersConfTestHelper.getHadoopUsers()[0]; // Remove leading / from filename if (filename.charAt(0) == '/') { filename = filename.substring(1); } String pathOps; if (perms == null) { pathOps = MessageFormat.format("/webhdfs/v1/{0}?user.name={1}&op=CREATE", filename, user); } else { pathOps = MessageFormat.format("/webhdfs/v1/{0}?user.name={1}&permission={2}&op=CREATE", filename, user, perms); } URL url = new URL(TestJettyHelper.getJettyURL(), pathOps); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestMethod("PUT"); conn.connect(); Assert.assertEquals(HttpURLConnection.HTTP_CREATED, conn.getResponseCode()); }
From source file:org.apache.taverna.component.profile.ComponentProfileImpl.java
private OntModel readOntologyFromURI(String ontologyId, String ontologyURI) { logger.info("Reading ontology for " + ontologyId + " from " + ontologyURI); OntModel model = createOntologyModel(); try {//w w w . ja va 2 s . com URL url = new URL(ontologyURI); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // CRITICAL: must be retrieved as correct content type conn.addRequestProperty("Accept", "application/rdf+xml,application/xml;q=0.9"); try (InputStream in = conn.getInputStream()) { // TODO Consider whether the encoding is handled right // ontologyModel.read(in, url.toString()); model.read(new StringReader(IOUtils.toString(in, "UTF-8")), url.toString()); } } catch (MalformedURLException e) { logger.error("Problem reading ontology " + ontologyId, e); return null; } catch (IOException e) { logger.error("Problem reading ontology " + ontologyId, e); return null; } catch (NullPointerException e) { // TODO Why is this different? logger.error("Problem reading ontology " + ontologyId, e); model = createOntologyModel(); } return model; }
From source file:org.runnerup.export.MapMyRunUploader.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;//from w ww. j a va 2s . c o m if ((s = connect()) != Status.OK) { return s; } TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); Pair<String, Sport> res = tcx.exportWithSport(mID, writer); Sport sport = res.second; conn = (HttpURLConnection) new URL(IMPORT_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); FormValues kv = new FormValues(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("baretcx", "1"); kv.put("tcx", writer.toString()); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = parse(in); conn.disconnect(); JSONObject result = obj.getJSONObject("result").getJSONObject("output").getJSONObject("result"); final String workout_id = result.getString("workout_id"); final String workout_key = result.getString("workout_key"); final JSONObject workout = result.getJSONObject("workout"); final String raw_workout_date = workout.getString("raw_workout_date"); String workout_type_id = workout.getString("workout_type_id"); if (sport != null && sport2mapmyrunMap.containsKey(sport)) workout_type_id = sport2mapmyrunMap.get(sport).toString(); kv.clear(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("workout_id", workout_id); kv.put("workout_key", workout_key); kv.put("workout_type_id", workout_type_id); kv.put("workout_description", "RunnerUp - " + raw_workout_date); kv.put("notes", tcx.getNotes()); kv.put("privacy_setting", "1"); // friends conn = (HttpURLConnection) new URL(UPDATE_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); in = new BufferedInputStream(conn.getInputStream()); obj = parse(in); conn.disconnect(); return Uploader.Status.OK; } } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.kuali.kfs.sys.service.DataObjectRestServiceTest.java
protected String sendQuery(String urlToRead, String requestMethod) { URL url;//from w ww. j a v a 2 s. com HttpURLConnection conn; BufferedReader rd; String line; String result = ""; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(requestMethod); Signature rsa = getDigitalSignatureService().getSignatureForSigning(); String moduleKeyStoreAlias = getJavaSecurityManagementService().getModuleKeyStoreAlias(); conn.addRequestProperty(KSBConstants.DIGITAL_SIGNATURE_HEADER, new String(Base64.encodeBase64(rsa.sign()), "UTF-8")); //conn.addRequestProperty(KSBConstants.KEYSTORE_ALIAS_HEADER, moduleKeyStoreAlias); Certificate cert = getJavaSecurityManagementService().getCertificate(moduleKeyStoreAlias); conn.addRequestProperty(KSBConstants.KEYSTORE_CERTIFICATE_HEADER, new String(Base64.encodeBase64(cert.getEncoded()), "UTF-8")); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result += line; } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:com.wadpam.guja.oauth2.social.NetworkTemplate.java
public <J> NetworkResponse<J> exchangeForResponse(String method, String url, Map<String, String> requestHeaders, Object requestBody, Class<J> responseClass, boolean followRedirects) { // so that we can read in case of Exception InputStream in = null;/*from w ww .ja v a2 s .c om*/ try { // expand url? if (null != requestBody && !CONTENT_METHODS.contains(method)) { Map<String, Object> paramMap = requestBody instanceof Map ? (Map) requestBody : MAPPER.convertValue(requestBody, Map.class); url = expandUrl(url, paramMap); } // create the connection URL u = new URL(url); HttpURLConnection con = (HttpURLConnection) u.openConnection(); con.setInstanceFollowRedirects(followRedirects); // override default method if (null != method) { con.setRequestMethod(method); } LOG.info("{} {}", method, url); // Accept if (null != accept) { con.addRequestProperty(ACCEPT, accept); LOG.trace("{}: {}", ACCEPT, accept); } // Authorization if (null != authorization) { con.addRequestProperty(AUTHORIZATION, authorization); LOG.trace("{}: {}", AUTHORIZATION, authorization); } // other request headers: String contentType = null; if (null != requestHeaders) { for (Entry<String, String> entry : requestHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue()); LOG.info("{}: {}", entry.getKey(), entry.getValue()); if (CONTENT_TYPE.equalsIgnoreCase(entry.getKey())) { contentType = entry.getValue(); } } } if (null != requestBody) { if (CONTENT_METHODS.contains(method)) { // content-type not specified in request headers? if (null == contentType) { contentType = MIME_JSON; con.addRequestProperty(CONTENT_TYPE, MIME_JSON); } con.setDoOutput(true); OutputStream out = con.getOutputStream(); if (MIME_JSON.equals(contentType)) { MAPPER.writeValue(out, requestBody); final String json = MAPPER.writeValueAsString(requestBody); LOG.debug("json Content: {}", json); } else { // application/www-form-urlencoded PrintWriter writer = new PrintWriter(out); if (requestBody instanceof String) { writer.print(requestBody); LOG.debug("Content: {}", requestBody); } else { Map<String, Object> params = MAPPER.convertValue(requestBody, Map.class); String content = expandUrl("", params); writer.print(content.substring(1)); LOG.debug("Content: {}", content.substring(1)); } writer.flush(); } out.close(); } } NetworkResponse<J> response = new NetworkResponse<J>(con.getResponseCode(), con.getHeaderFields(), con.getResponseMessage()); LOG.info("HTTP {} {}", response.getCode(), response.getMessage()); // response content to read and parse? if (null != con.getContentType()) { final String responseType = con.getContentType(); LOG.debug("Content-Type: {}", responseType); in = con.getInputStream(); if (con.getContentType().startsWith(MIME_JSON)) { response.setBody(MAPPER.readValue(in, responseClass)); LOG.debug("Response JSON: {}", response.getBody()); } else if (String.class.equals(responseClass)) { String s = readResponseAsString(in, responseType); LOG.info("Read {} bytes from {}", s.length(), con.getContentType()); response.setBody((J) s); } else if (400 <= response.getCode()) { String s = readResponseAsString(in, responseType); LOG.warn(s); } in.close(); } return response; } catch (IOException ioe) { if (null != in) { try { BufferedReader br = new BufferedReader(new InputStreamReader(in)); String s; while (null != (s = br.readLine())) { LOG.warn(s); } } catch (IOException ignore) { } } throw new RuntimeException(String.format("NetworkTemplate.exchange: %s", ioe.getMessage()), ioe); } }
From source file:com.denimgroup.threadfix.service.defects.utils.RestUtilsImpl.java
@Nonnull private InputStream postUrl(String urlString, String data, String username, String password, String contentType) {//from w w w .j a v a 2 s . com URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { LOG.warn("URL used for POST was bad: '" + urlString + "'"); throw new RestUrlException(e, "Received a malformed server URL."); } HttpURLConnection httpConnection = null; OutputStreamWriter outputWriter = null; try { if (proxyService == null) { httpConnection = (HttpURLConnection) url.openConnection(); } else { httpConnection = proxyService.getConnectionWithProxyConfig(url, classToProxy); } setupAuthorization(httpConnection, username, password); httpConnection.addRequestProperty("Content-Type", contentType); httpConnection.addRequestProperty("Accept", contentType); httpConnection.setDoOutput(true); outputWriter = new OutputStreamWriter(httpConnection.getOutputStream()); outputWriter.write(data); outputWriter.flush(); InputStream is = httpConnection.getInputStream(); return is; } catch (IOException e) { LOG.warn("IOException encountered trying to post to URL with message: " + e.getMessage()); if (httpConnection == null) { LOG.warn( "HTTP connection was null so we cannot do further debugging of why the HTTP request failed"); } else { try { InputStream errorStream = httpConnection.getErrorStream(); if (errorStream == null) { LOG.warn("Error stream from HTTP connection was null"); } else { LOG.warn( "Error stream from HTTP connection was not null. Attempting to get response text."); setPostErrorResponse(IOUtils.toString(errorStream)); LOG.warn("Error text in response was '" + getPostErrorResponse() + "'"); throw new RestIOException(e, getPostErrorResponse(), "Unable to get response from server. Error text was: " + getPostErrorResponse(), getStatusCode(httpConnection)); } } catch (IOException e2) { LOG.warn("IOException encountered trying to read the reason for the previous IOException: " + e2.getMessage(), e2); throw new RestIOException(e2, "Unable to read response from server." + e2.getMessage(), getStatusCode(httpConnection)); } } throw new RestIOException(e, "Unable to read response from server." + e.toString()); } finally { if (outputWriter != null) { try { outputWriter.close(); } catch (IOException e) { LOG.warn("Failed to close output stream in postUrl.", e); } } } }
From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java
private void appendRequestHeaders(final HttpURLConnection conn, final Collection<RequestHeader> headers) { for (RequestHeader header : headers) { if (header != null) { conn.addRequestProperty(header.getKey(), header.getValue()); }/*from w w w .j a v a 2s .c om*/ } }