List of usage examples for java.net HttpURLConnection getContentType
public String getContentType()
From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java
void process() throws Exception { ClientId client = ServerConf.getIdentifier().getOwner(); ServiceId service = getServiceId();/*from www. java2s . c o m*/ log.trace("process({}, {})", client, service); SoapMessageImpl message = createMessage(client, service); if (log.isTraceEnabled()) { log.trace("message:\n{}", message.getXml()); } HttpURLConnection connection = createConnection(message); try (InputStream in = connection.getInputStream(); SoapDecoderCallback callback = new SoapDecoderCallback()) { SoapMessageDecoder decoder = new SoapMessageDecoder(connection.getContentType(), callback); decoder.parse(in); } }
From source file:com.adamrosenfield.wordswithcrosses.net.DerStandardDownloader.java
protected Reader getURLReader(HttpURLConnection conn) throws IOException, MalformedURLException, UnsupportedEncodingException { InputStream in = (InputStream) conn.getContent(); String encoding = conn.getContentEncoding(); String type = conn.getContentType(); if (encoding == null) { Matcher m = P_CHARSET_IN_TYPE.matcher(type); if (m.matches()) { encoding = m.group(1);//from w ww. ja v a2 s . c om } else { encoding = "ISO-8859-1"; } } Reader r = new InputStreamReader(in, encoding); return r; }
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected void verifyResponseStatus(HttpURLConnection con) throws IOException { if (con.getResponseCode() / 100 != 2) { String msg = "Failed to call " + con.getURL() + " : " + con.getResponseCode() + ' ' + con.getResponseMessage(); InputStream es = con.getErrorStream(); String ct = con.getContentType(); if (ct != null) { HttpHeader contentType = HttpHeader.parse(ct); if (contentType.value.equals("application/json")) { // if the error is JSON, parse it if (es != null) { JSONObject error = JSONObject .fromObject(IOUtils.toString(es, contentType.getSubHeader("charset", "UTF-8"))); throw new ServerException(msg, error, con.getResponseCode(), con.getResponseMessage(), con.getURL()); }/* w ww . j a v a2 s.c o m*/ } } if (es != null) msg += "\n" + IOUtils.toString(es); throw new IOException(msg); } }
From source file:org.apache.olingo.odata2.fit.basic.FitLoadTest.java
@Test public void useJavaHttpClient() throws IOException { final URI uri = URI.create(getEndpoint().toString() + "$metadata"); for (int i = 0; i < LOOP_COUNT; i++) { HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty(HttpHeaders.ACCEPT, HttpContentType.WILDCARD); connection.connect();//from w w w.j ava 2 s. co m assertEquals(HttpStatusCodes.OK.getStatusCode(), connection.getResponseCode()); assertEquals(HttpContentType.APPLICATION_XML_UTF8, connection.getContentType()); } }
From source file:com.ehsy.solr.util.SimplePostTool.java
private static boolean checkResponseCode(HttpURLConnection urlc) throws IOException { if (urlc.getResponseCode() >= 400) { warn("Solr returned an error #" + urlc.getResponseCode() + " (" + urlc.getResponseMessage() + ") for url: " + urlc.getURL()); Charset charset = StandardCharsets.ISO_8859_1; final String contentType = urlc.getContentType(); // code cloned from ContentStreamBase, but post.jar should be standalone! if (contentType != null) { int idx = contentType.toLowerCase(Locale.ROOT).indexOf("charset="); if (idx > 0) { charset = Charset.forName(contentType.substring(idx + "charset=".length()).trim()); }//w w w. j av a2 s . co m } // Print the response returned by Solr try (InputStream errStream = urlc.getErrorStream()) { if (errStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(errStream, charset)); final StringBuilder response = new StringBuilder("Response: "); int ch; while ((ch = br.read()) != -1) { response.append((char) ch); } warn(response.toString().trim()); } } return false; } return true; }
From source file:github.srlee309.lessWrongBookCreator.scraper.PostSectionExtractor.java
public boolean downloadFileFromURL(String fetchUrl, File outputFile) throws IOException, FileNotFoundException, IOException { HttpURLConnection c; //save file URL url = new URL(fetchUrl); c = (HttpURLConnection) url.openConnection(); //set cache and request method settings c.setUseCaches(false);//from www. ja va 2 s. c o m c.setDoOutput(false); //set other headers c.setRequestProperty("Content-Type", "image/jpeg"); System.out.println(c.getContentType()); //connect c.connect(); BufferedInputStream in = new BufferedInputStream(c.getInputStream()); OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[256]; int n = 0; while ((n = in.read(buf)) >= 0) { out.write(buf, 0, n); } out.flush(); out.close(); return true; }
From source file:org.sonatype.nexus.artifactorybridge.ArtifactoryRedirectorPlexusResource.java
@Override public Object get(Context context, Request request, Response response, Variant variant) throws ResourceException { // sample artifactory URL // http://localhost:8083/artifactory/main-local/nxcm259/released/1.0/released-1.0.pom String nexusUrl = request.getHostRef().toString(); String servletPath = request.getOriginalRef().getPath(); String nexusPath = urlConverter.convertDownload(servletPath); if (nexusPath == null) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Unable to map artifact request '" + servletPath + "'"); }// w ww.j ava2 s. co m HttpURLConnection urlConn = null; try { URL url = new URL(nexusUrl + nexusPath); getLogger().debug("Redirecting GET request from:" + servletPath + " to: " + url); urlConn = (HttpURLConnection) url.openConnection(); copyHeaders(request, urlConn); String type = urlConn.getContentType(); return new URLInputStreamRepresentation(type, urlConn.getInputStream(), urlConn); } catch (Throwable e) { int statusCode = getReturnCode(urlConn); if (statusCode == 401) { getLogger().debug("Received 401 from Nexus, inserting Challenge request to the client."); response.setChallengeRequest( new ChallengeRequest(ChallengeScheme.HTTP_BASIC, "Sonatype Nexus Repository Manager")); } throw new ResourceException(statusCode, e); } }
From source file:org.n52.wps.test.Wps4rIT.java
@Test public void csvResponseReferenceWorks() throws XmlException, IOException { URL resource = Wps4rIT.class.getResource("/R/ExecuteTestCSV.xml"); XmlObject xmlPayload = XmlObject.Factory.parse(resource); String payload = xmlPayload.toString(); payload = payload.replace("@@@ref@@@", Boolean.toString(true)); String response = PostClient.sendRequest(wpsUrl, payload); assertThat("Response is not an exception", response, not(containsString("ExceptionReport"))); assertThat("Response contains mime type", response, containsString("mimeType=\"text/csv\"")); String urlString = response.substring(response.indexOf("http", response.indexOf("text/csv"))); urlString = urlString.substring(0, urlString.indexOf("\"")); URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect();/*from ww w .j a v a2 s. co m*/ String contentType = connection.getContentType(); assertThat("Response content type is correct", contentType, is("text/csv")); StringWriter writer = new StringWriter(); IOUtils.copy(connection.getInputStream(), writer); String csv = writer.toString(); assertThat("CSV file contains test data names", csv, containsString("\"cadmium\",\"copper\",\"lead\",\"zinc\"")); }
From source file:fr.ybonnel.simpleweb4j.util.SimpleWebTestUtil.java
public UrlResponse doMethod(String requestMethod, String path, String body) throws Exception { URL url = new URL("http://localhost:" + port + path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(requestMethod); if (body != null) { connection.setDoOutput(true);//from www . j a v a 2 s . c o m connection.getOutputStream().write(body.getBytes()); } connection.connect(); UrlResponse response = new UrlResponse(); response.status = connection.getResponseCode(); response.headers = connection.getHeaderFields(); response.contentType = connection.getContentType(); if (response.status >= 400) { if (connection.getErrorStream() != null) { response.body = IOUtils.toString(connection.getErrorStream()); } } else { if (connection.getInputStream() != null) { response.body = IOUtils.toString(connection.getInputStream()); } } return response; }
From source file:org.opentestsystem.shared.test.interactioncontext.FastInteractionResponse.java
FastInteractionResponse(FastInteractionContext interactionContext, InputStream is, HttpURLConnection connection, long timeout, long t_timeout) throws IOException { _interactionContext = interactionContext; _timeout = timeout;//from www. j ava 2 s . c o m _t_timeout = t_timeout; // Get the response _requestUrl = connection.getURL(); _bytes = IOUtils.toByteArray(is); _responseHeaders = connection.getHeaderFields(); connection.getContentType(); String message = connection.getResponseMessage(); if (message != null) { String[] messageParts = StringUtils.split(message, null, 3); if (messageParts.length > 0) { _httpVersion = messageParts[0]; } if (messageParts.length > 1) { try { _status = Integer.valueOf(messageParts[1]); } catch (Exception e) { // Do nothing: an invalid HTTP status code!! } } if (messageParts.length > 2) { _statusMessage = messageParts[2]; } } }