List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:org.dcm4che3.tool.wadors.WadoRS.java
private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException { URL newUrl = new URL(main.getUrl()); LOG.info("WADO-RS URL: {}", newUrl); HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setDoOutput(true);// w ww. j av a 2 s . c o m connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); String[] acceptHeaders = compileAcceptHeader(main.acceptTypes); LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders)); for (String acceptStr : acceptHeaders) connection.addRequestProperty("Accept", acceptStr); if (main.getRequestTimeOut() != null) { connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut())); connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut())); } connection.setUseCaches(false); int responseCode = connection.getResponseCode(); String responseMessage = connection.getResponseMessage(); boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST; if (!isErrorCase) { InputStream in = null; if (connection.getHeaderField("content-type").contains("application/json") || connection.getHeaderField("content-type").contains("application/zip")) { String headerPath; in = connection.getInputStream(); if (main.dumpHeader) headerPath = writeHeader(connection.getHeaderFields(), new File(main.outDir, "out.json" + "-head")); else { headerPath = connection.getHeaderField("content-location"); } File f = new File(main.outDir, connection.getHeaderField("content-type").contains("application/json") ? "out.json" : "out.zip"); Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING); main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath()); } else { if (main.dumpHeader) dumpHeader(main, connection.getHeaderFields()); in = connection.getInputStream(); try { File spool = new File(main.outDir, "Spool"); Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING); String boundary; BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool))); boundary = (rdr.readLine()); boundary = boundary.substring(2, boundary.length()); rdr.close(); FileInputStream fin = new FileInputStream(spool); new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() { @Override public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException { Map<String, List<String>> headerParams = partIn.readHeaderParams(); String mediaType; String contentType = headerParams.get("content-type").get(0); if (contentType.contains("transfer-syntax")) mediaType = contentType.split(";")[0]; else mediaType = contentType; // choose writer if (main.isMetadata) { main.writerType = ResponseWriter.XML; } else { if (mediaType.equalsIgnoreCase("application/dicom")) { main.writerType = ResponseWriter.DICOM; } else if (isBulkMediaType(mediaType)) { main.writerType = ResponseWriter.BULK; } else { throw new IllegalArgumentException("Unknown media type " + "returned by server, media type = " + mediaType); } } try { main.writerType.readBody(main, partIn, headerParams); } catch (Exception e) { System.out.println("Error parsing media type to determine extension" + e); } } private boolean isBulkMediaType(String mediaType) { if (mediaType.contains("octet-stream")) return true; for (Field field : MediaTypes.class.getFields()) { try { if (field.getType().equals(String.class)) { String tmp = (String) field.get(field); if (tmp.equalsIgnoreCase(mediaType)) return true; } } catch (Exception e) { System.out.println("Error deciding media type " + e); } } return false; } }); fin.close(); spool.delete(); } catch (Exception e) { System.out.println("Error parsing Server response - " + e); } } } else { LOG.error("Server returned {} - {}", responseCode, responseMessage); } connection.disconnect(); main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances); return new SimpleHTTPResponse(responseCode, responseMessage); }
From source file:org.inaetics.pubsub.demo.config.EtcdWrapper.java
public JsonNode refreshTTL(String key, int timeToLive) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url + key).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); String query = String.format("refresh=%s&ttl=%s&prevExist=%s", URLEncoder.encode("true", charset), URLEncoder.encode(timeToLive + "", charset), URLEncoder.encode("true", charset)); try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); }//from w w w .j a va 2 s . com InputStream response = connection.getInputStream(); JsonNode result = new ObjectMapper().readTree(response); response.close(); AddEtcdIndex(result, Long.parseLong(connection.getHeaderFields().get("X-Etcd-Index").get(0))); return result; }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception { HttpURLConnection urlConnection = null; try {//from ww w . j a v a 2 s . co m urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("PUT"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlConnection.setDoOutput(true); if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); urlConnection.setRequestProperty(key, headers.get(key)); } } OutputStream out = urlConnection.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); writer.close(); } catch (IOException e) { throw new Exception("IOException while puting data", e); } finally { if (out != null) { out.close(); } } // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.android.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }//from w w w. j av a2 s . c om map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:nu.nethome.home.items.web.proxy.HomeCloudConnection.java
private HttpResponse performLocalRequest(HttpRequest request) throws IOException { HttpResponse httpResponse;/*from www . j av a 2 s .c om*/ HttpURLConnection connection = (HttpURLConnection) new URL(localURL + request.url).openConnection(); for (String header : request.headers) { String parts[] = header.split(":"); connection.setRequestProperty(parts[0].trim(), parts[1].trim()); } ByteArrayBuffer baf = new ByteArrayBuffer(50); try (InputStream response = connection.getInputStream()) { BufferedInputStream bis = new BufferedInputStream(response); int read; int bufSize = 512; byte[] buffer = new byte[bufSize]; while (true) { read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } } catch (IOException e) { return new HttpResponse(systemId, "", new String[0], CHALLENGE); } Map<String, List<String>> map = connection.getHeaderFields(); String headers[] = new String[map.size()]; int i = 0; for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); headers[i++] = entry.getKey() + ":" + entry.getValue().get(0); } httpResponse = new HttpResponse(systemId, new String(Base64.encodeBase64(baf.toByteArray())), headers, CHALLENGE); return httpResponse; }
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///ww w . ja v a 2 s . com @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:com.continusec.client.ContinusecClient.java
/** * Package private common method for making underlying HTTP requests to API server. * @param method the HTTP method to use. * @param path the path underneath this account to use. * @param data for PUT and POST methods, the data (if any to) to send in body. * @param extraHeaders additional headers to include in the request * @return the body and headers./*from w ww . ja va 2 s . c o m*/ * @throws ContinusecException for any network errors, or non 200 responses. */ protected ResponseData makeRequest(String method, String path, byte[] data, String[][] extraHeaders) throws ContinusecException { try { URL url = new URL(this.baseURL + "/v1/account/" + this.account + path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); if (this.apiKey != null) { conn.setRequestProperty("Authorization", "Key " + this.apiKey); } if (extraHeaders != null) { for (int i = 0; i < extraHeaders.length; i++) { conn.setRequestProperty(extraHeaders[i][0], extraHeaders[i][1]); } } if (method.equals("POST") || method.equals("PUT")) { conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); if (data != null && data.length > 0) { out.write(data); } out.flush(); out.close(); } conn.connect(); int code = conn.getResponseCode(); switch (code) { case 200: return new ResponseData(IOUtils.toByteArray(conn.getInputStream()), conn.getHeaderFields()); case 400: throw new InvalidRangeException(); case 403: throw new UnauthorizedAccessException(); case 404: throw new ObjectNotFoundException(); case 409: throw new ObjectConflictException(); default: throw new InternalErrorException(); } } catch (MalformedURLException e) { throw new ContinusecNetworkException(e); } catch (IOException e) { throw new ContinusecNetworkException(e); } }
From source file:org.wso2.appserver.integration.tests.webappsampleservice.WebAppSampleTestCase.java
private int getResponseCode(String path, ByteChunk out, int readTimeout, Map<String, List<String>> reqHead, Map<String, List<String>> resHead) throws Exception { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false);/* ww w .j a va 2s .c om*/ connection.setReadTimeout(readTimeout); if (reqHead != null) { for (Map.Entry<String, List<String>> entry : reqHead.entrySet()) { StringBuilder valueList = new StringBuilder(); for (String value : entry.getValue()) { if (valueList.length() > 0) { valueList.append(','); } valueList.append(value); } connection.setRequestProperty(entry.getKey(), valueList.toString()); } } connection.connect(); int rc = connection.getResponseCode(); if (resHead != null) { Map<String, List<String>> head = connection.getHeaderFields(); resHead.putAll(head); } if (rc == HttpServletResponse.SC_OK) { InputStream is = connection.getInputStream(); BufferedInputStream bis = null; try { bis = new BufferedInputStream(is); byte[] buf = new byte[2048]; int rd = 0; while ((rd = bis.read(buf)) > 0) { out.append(buf, 0, rd); } } finally { if (bis != null) { bis.close(); } } } return rc; }
From source file:org.inaetics.pubsub.demo.config.EtcdWrapper.java
/** * Put a node in etcd/*from ww w . j av a2 s.c o m*/ * * @param key * @param value * @return * @throws UnsupportedEncodingException * @throws IOException */ public JsonNode put(String key, String value, int timeToLive) throws UnsupportedEncodingException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url + key).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestMethod("PUT"); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); String query = ""; if (timeToLive > 0) { query = String.format("value=%s&ttl=%d", URLEncoder.encode(value, charset), timeToLive); } else { query = String.format("value=%s", URLEncoder.encode(value, charset)); } try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); } InputStream response = connection.getInputStream(); JsonNode result = new ObjectMapper().readTree(response); response.close(); AddEtcdIndex(result, Long.parseLong(connection.getHeaderFields().get("X-Etcd-Index").get(0))); return result; }
From source file:net.sparkeh.magisterlib.host.MagisterRequest.java
public void sendRequest(MagisterHost host) throws MalformedURLException, IOException { URL obj = new URL(host.getApiHost() + subUrl); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(reqOut.toString()); con.setRequestProperty("User-Agent", userAgent); con.setRequestProperty("Content-Type", contentType); for (Entry<String, String> e : this.headersIn.entrySet()) { con.setRequestProperty(e.getKey(), e.getValue()); }/*from w w w .j a va 2s. com*/ if (reqOut != RequestType.GET && this.bodyOut.length() > 0) { con.setDoOutput(true); con.getOutputStream().write(this.bodyOut.getBytes("UTF-8")); } this.responseCodeIn = con.getResponseCode(); System.out.println("\nSending '" + reqOut.toString() + "' request to URL : " + obj.getPath()); System.out.println("Response Code : " + this.responseCodeIn); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); this.headersIn.clear(); for (String key : con.getHeaderFields().keySet()) { this.headersIn.put(key, con.getHeaderField(key)); } this.bodyIn = response.toString(); }