List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:org.openbravo.test.webservice.BaseWSTest.java
/** * Executes a DELETE HTTP request, the wsPart is appended to the {@link #getOpenbravoURL()}. * /*w w w . j a v a 2 s .c o m*/ * @param wsPart * the actual webservice part of the url, is appended to the openbravo url ( * {@link #getOpenbravoURL()}), includes any query parameters * @param expectedResponse * the expected HTTP response code */ protected void doDirectDeleteRequest(String wsPart, int expectedResponse) { try { final HttpURLConnection hc = createConnection(wsPart, "DELETE"); hc.connect(); assertEquals(expectedResponse, hc.getResponseCode()); assertTrue("Content type not set in delete response", hc.getContentType() != null); // disabled, see here: https://issues.openbravo.com/view.php?id=10236 // assertTrue("Content encoding not set in delete response", hc.getContentEncoding() != null); } catch (final Exception e) { throw new OBException(e); } }
From source file:org.apache.olingo.fit.tecsvc.http.BasicHttpITCase.java
@Test public void testIEEE754ParameterViaAcceptHeader() throws Exception { final URL url = new URL(SERVICE_URI + "ESAllPrim(32767)"); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;IEEE754Compatible=true"); connection.connect();//from w w w . java2 s. c o m assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_IEEE754_COMPATIBLE, "true"), ContentType.create(connection.getContentType())); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyDecimal\":\"34\"")); assertTrue(content.contains("\"PropertyInt64\":\"9223372036854775807\"")); }
From source file:org.apache.olingo.fit.tecsvc.http.BasicHttpITCase.java
@Test public void testIEEE754ParameterContentNegotiation() throws Exception { final URL url = new URL(SERVICE_URI + "ESAllPrim(32767)?$format=application/json;IEEE754Compatible=true"); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;IEEE754Compatible=false"); connection.connect();/*w w w.j a va2s. co m*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_IEEE754_COMPATIBLE, "true"), ContentType.create(connection.getContentType())); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyDecimal\":\"34\"")); assertTrue(content.contains("\"PropertyInt64\":\"9223372036854775807\"")); }
From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java
private String getContentEncoding(HttpURLConnection http) { if (http.getContentEncoding() != null) { return http.getContentEncoding(); }/*from ww w . j a v a2 s . co m*/ // Parse Content-Type header for encoding try { ContentType contentType = new ContentType(http.getContentType()); if (!isEmpty(contentType.getParameter(PARAM_CHARSET))) { return contentType.getParameter(PARAM_CHARSET); } } catch (ParseException e) { log.trace("Unable to parse Content-Type header \"{}\": {}", http.getContentType(), e.toString()); } return null; }
From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java
public void ensureRunning() { if (original != null) { return;//from w ww. j ava 2 s . co m } // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController Jenkins jenkins = injector.getInstance(Jenkins.class); List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url"); if (sites.size() != 1) { // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites); return; } UpdateCenterMetadata ucm; try { ucm = ucmd.get(jenkins); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot load data for mock update center", x); return; } JSONObject all; try { all = new JSONObject(ucm.originalJSON); all.remove("signature"); JSONObject plugins = all.getJSONObject("plugins"); LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides"); for (PluginMetadata meta : ucm.plugins.values()) { String name = meta.getName(); String version = meta.getVersion(); JSONObject plugin = plugins.optJSONObject(name); if (plugin == null) { LOGGER.log(Level.INFO, "adding plugin {0}", name); plugin = new JSONObject().accumulate("name", name); plugins.put(name, plugin); } plugin.put("url", name + ".hpi"); updating(plugin, "version", version); updating(plugin, "gav", meta.gav); updating(plugin, "requiredCore", meta.requiredCore().toString()); updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> { try { return new JSONObject().accumulate("name", d.name).accumulate("version", d.version) .accumulate("optional", d.optional); } catch (JSONException x) { throw new AssertionError(x); } }).collect(Collectors.toList()))); plugin.remove("sha1"); } } catch (JSONException x) { LOGGER.log(Level.WARNING, "cannot prepare mock update center", x); return; } HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")) .add(new ResponseContent()).add(new RequestConnControl()).build(); UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper(); String json = "updateCenter.post(\n" + all + "\n);"; handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); }); handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> { String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1"); PluginMetadata meta = ucm.plugins.get(plugin); if (meta == null) { LOGGER.log(Level.WARNING, "no such plugin {0}", plugin); response.setStatusCode(HttpStatus.SC_NOT_FOUND); return; } File local = meta.resolve(injector, meta.getVersion()); LOGGER.log(Level.INFO, "serving {0}", local); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new FileEntity(local)); }); handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> { String location = original.replace("/update-center.json", request.getRequestLine().getUri()); LOGGER.log(Level.INFO, "redirect to {0}", location); /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true): response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader("Location", location); */ HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection(); uc.setInstanceFollowRedirects(true); // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json byte[] data = IOUtils.toByteArray(uc); String contentType = uc.getContentType(); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType))); }); server = ServerBootstrap.bootstrap(). // could setLocalAddress if using a JenkinsController that requires it setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()) .create(); try { server.start(); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot start mock update center", x); return; } original = sites.get(0); // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json"; LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override }); jenkins.runScript( "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override); }
From source file:fr.gael.dhus.api.SearchController.java
@PreAuthorize("hasRole('ROLE_SEARCH')") @RequestMapping(value = "/search") public void search(Principal principal, @RequestParam(value = "q") String orginal_query, @RequestParam(value = "rows", defaultValue = "") String rows_str, @RequestParam(value = "start", defaultValue = "") String start_str, @RequestParam(value = "format", defaultValue = "") String format, HttpServletResponse res) throws IOException, JSONException { User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); ServerConfiguration dhusServer = configurationManager.getServerConfiguration(); String query = convertQuery(orginal_query); LOGGER.info("Rewritted Query: " + query); String urlStr = "&dhusLongName=" + configurationManager.getNameConfiguration().getLongName() + "&dhusServer=" + dhusServer.getExternalUrl(); urlStr += "&originalQuery=" + orginal_query; urlStr = urlStr.replace(" ", "%20"); int skip = 0; int rows = 10; if (rows_str != null && !rows_str.isEmpty()) { try {//from ww w . ja va2 s . c o m rows = Integer.parseInt(rows_str); urlStr += "&rows=" + rows_str; } catch (NumberFormatException nfe) { /* noting to do : keep the default value */ } } if (start_str != null && !start_str.isEmpty()) { try { skip = Integer.parseInt(start_str); urlStr += "&start=" + start_str; } catch (NumberFormatException nfe) { /* noting to do : keep the default value */ } } URLEncoder.encode(urlStr, "UTF-8"); actionRecordWritterDao.search(orginal_query, skip, rows, user); // solr is only accessible from local server String local_url = dhusServer.getUrl(); URL obj = new URL(local_url + "/solr/dhus/select?" + query + "&wt=xslt&tr=opensearch_atom.xsl" + urlStr); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); try (InputStream is = con.getInputStream()) { try (ServletOutputStream os = res.getOutputStream()) { res.setStatus(HttpServletResponse.SC_OK); if ("json".equalsIgnoreCase(format)) { res.setContentType("application/json"); toJSON(is, os); } else { res.setContentType(con.getContentType()); IOUtils.copy(is, os); } } } }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
private HttpEntity asEntity(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream in;/*from w w w . j a v a 2 s . co m*/ try { in = connection.getInputStream(); } catch (IOException e) { in = connection.getErrorStream(); } entity.setContent(in); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:com.android.browser.search.OpenSearchSearchEngine.java
/** * Executes a GET request and returns the response content. * * @param urlString Request URI.//from w w w . j a v a 2 s . c o m * @return The response content. This is the empty string if the response * contained no content. */ public String readUrl(String urlString) { try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", USER_AGENT); urlConnection.setConnectTimeout(HTTP_TIMEOUT_MS); if (urlConnection.getResponseCode() == 200) { final Charset responseCharset; try { responseCharset = ResponseUtils.responseCharset(urlConnection.getContentType()); } catch (UnsupportedCharsetException ucse) { Log.i(TAG, "Unsupported response charset", ucse); return null; } catch (IllegalCharsetNameException icne) { Log.i(TAG, "Illegal response charset", icne); return null; } byte[] responseBytes = Streams.readFully(urlConnection.getInputStream()); return new String(responseBytes, responseCharset); } else { Log.i(TAG, "Suggestion request failed"); return null; } } catch (IOException e) { Log.w(TAG, "Error", e); return null; } }
From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java
/** * HTTP????,??/*from ww w . jav a2 s . c om*/ * @param connection * @return HttpEntity */ private HttpEntity entityFromURLConnwction(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream = null; try { inputStream = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); inputStream = connection.getErrorStream(); } // TODO : GZIP entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:org.holistic.ws_proxy.WSProxyHelper.java
private void doGet(HttpServletRequest req, HttpServletResponse resp) throws Exception { HttpURLConnection m_objURLConnection = null; m_objURLConnection = openurl(get_request(req)); // resp.setStatus(m_objURLConnection.getResponseCode()); set_headers2urlconn(req, m_objURLConnection); m_objURLConnection.setRequestProperty("host", m_objURLConnection.getURL().getHost() + ":" + m_objURLConnection.getURL().getPort()); resp.setStatus(m_objURLConnection.getResponseCode()); if (m_objURLConnection.getContentType() != null) resp.setContentType(m_objURLConnection.getContentType()); get_endpointstream(resp, m_objURLConnection); }