List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:com.vimc.ahttp.HurlWorker.java
@Override public HttpResponse doHttpRquest(Request<?> request) throws IOException { String url = request.getUrl(); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); }//from w w w. j av a 2 s.com url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); addHeadersIfExists(request, connection); setConnectionParametersByRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 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(protocolVersion, 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:com.kubeiwu.commontool.khttp.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());// map.putAll(additionalHeaders);// ww w. ja v a 2 s. c o m if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url);// ?url if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) {// header connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 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(protocolVersion, 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); //cookie? String key = header.getKey(); List<String> values = header.getValue(); if (key.equalsIgnoreCase("set-cookie")) { StringBuilder cookieString = new StringBuilder(); for (String value : values) { cookieString.append(value).append("\n");// \ncookie?? } cookieString.deleteCharAt(cookieString.length() - 1); Header h = new BasicHeader(header.getKey(), cookieString.toString()); response.addHeader(h); } else { Header h = new BasicHeader(header.getKey(), values.get(0)); response.addHeader(h); } } } System.out.println("performRequest---999999-getStatusLine=" + response.getStatusLine()); return response; }
From source file:org.aselect.authspserver.authsp.delegator.HTTPDelegate.java
public int authenticate(Map<String, String> requestparameters, Map<String, List<String>> responseparameters) throws DelegateException { String sMethod = "authenticate"; int iReturnCode = -1; AuthSPSystemLogger _systemLogger;//ww w .j av a 2s. c om _systemLogger = AuthSPSystemLogger.getHandle(); _systemLogger.log(Level.FINEST, sModule, sMethod, "requestparameters=" + requestparameters + " , responseparameters=" + responseparameters); StringBuffer data = new StringBuffer(); String sResult = ""; try { final String EQUAL_SIGN = "="; final String AMPERSAND = "&"; final String NEWLINE = "\n"; for (String key : requestparameters.keySet()) { data.append(URLEncoder.encode(key, "UTF-8")); data.append(EQUAL_SIGN).append(URLEncoder.encode( ((String) requestparameters.get(key) == null) ? "" : (String) requestparameters.get(key), "UTF-8")); data.append(AMPERSAND); } if (data.length() > 0) data.deleteCharAt(data.length() - 1); // remove last AMPERSAND // _systemLogger.log(Level.FINE, sModule, sMethod, "url=" + url.toString() + " data={" + data.toString() + "}"); // no data shown in production environment HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Basic authentication if (this.delegateuser != null) { byte[] bEncoded = Base64 .encodeBase64((this.delegateuser + ":" + (delegatepassword == null ? "" : delegatepassword)) .getBytes("UTF-8")); String encoded = new String(bEncoded, "UTF-8"); conn.setRequestProperty("Authorization", "Basic " + encoded); _systemLogger.log(Level.FINEST, sModule, sMethod, "Using basic authentication, user=" + this.delegateuser); } // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // They (the delegate party) don't accept charset !! conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data.toString()); wr.flush(); wr.close(); // Get the response iReturnCode = conn.getResponseCode(); Map<String, List<String>> hFields = conn.getHeaderFields(); _systemLogger.log(Level.FINEST, sModule, sMethod, "response=" + iReturnCode); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; // Still to decide on response protocol while ((line = rd.readLine()) != null) { sResult += line; } _systemLogger.log(Level.INFO, sModule, sMethod, "sResult=" + sResult); // Parse response here // For test return request parameters responseparameters.putAll(hFields); rd.close(); } catch (IOException e) { _systemLogger.log(Level.INFO, sModule, sMethod, "Error while reading sResult data, maybe no data at all. sResult=" + sResult); } catch (NumberFormatException e) { throw new DelegateException("Sending authenticate request, using \'" + this.url.toString() + "\' failed due to number format exception! " + e.getMessage(), e); } catch (Exception e) { throw new DelegateException("Sending authenticate request, using \'" + this.url.toString() + "\' failed (progress=" + iReturnCode + ")! " + e.getMessage(), e); } return iReturnCode; }
From source file:com.xjb.volley.toobox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from www . ja va 2 s. c om map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { try { connection.addRequestProperty(headerName, map.get(headerName)); } catch (Exception e) { } } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 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(protocolVersion, 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) { synchronized (HurlStack.class) { if (header.getKey().equals("Set-Cookie")) { String cookie = ""; List<String> list = header.getValue(); if (list.size() > 0) { for (int i = 0; i < list.size(); i++) { if (list.get(i).contains("IHOME_FRONT_SID")) { String[] ss = list.get(i).split(";"); cookie = ss[0]; } } } Header h = new BasicHeader(header.getKey(), cookie); response.addHeader(h); } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } } return response; }
From source file:com.dao.ShopThread.java
private boolean doPTShop() throws Exception { long startTime = System.currentTimeMillis(); // loadCookie(); boolean result = true; LogUtil.webPrintf("??..."); String postParams = addPTDynamicParams(); LogUtil.webPrintf("???"); LogUtil.webPrintf("?..."); HttpURLConnection loginConn = getHttpPostConn(this.ptshopurl); loginConn.setRequestProperty("Host", "danbao.5173.com"); loginConn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); LogUtil.debugPrintf("?HEADER===" + loginConn.getRequestProperties()); DataOutputStream wr = new DataOutputStream(loginConn.getOutputStream()); wr.writeBytes(postParams);// w w w . j a v a 2 s .c o m wr.flush(); wr.close(); int responseCode = loginConn.getResponseCode(); LogUtil.debugPrintf("\nSending 'POST' request to URL : " + this.ptshopurl); LogUtil.debugPrintf("Post parameters : " + postParams); LogUtil.debugPrintf("Response Code : " + responseCode); Map<String, List<String>> header = loginConn.getHeaderFields(); LogUtil.debugPrintf("??HEADER===" + header); List<String> cookie = header.get("Set-Cookie"); if (cookie == null || cookie.size() == 0) { result = false; LogUtil.webPrintf("?!"); } else { LogUtil.webPrintf("??!"); LogUtil.debugPrintf("cookie====" + cookie); LogUtil.debugPrintf("Location :" + loginConn.getURL().toString()); setCookies(cookie); LogUtil.webPrintf("?..."); String payurl = getPayKey(loginConn, "db"); LogUtil.webPrintf("??"); if (payurl != null && !payurl.equals("")) { LogUtil.debugPrintf("?url:" + payurl); LogUtil.webPrintf("..."); pay(payurl); LogUtil.webPrintf("?"); } else { LogUtil.webPrintf("?"); LogUtil.debugPrintf("?url"); } } return result; }
From source file:com.portfolio.data.attachment.XSLService.java
void RetrieveAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { /// Receive answer InputStream in;/*from ww w. j av a2 s.com*/ try { in = connection.getInputStream(); } catch (Exception e) { System.out.println(e.toString()); in = connection.getErrorStream(); } String ref = null; if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } /// Write back data DataInputStream stream = new DataInputStream(in); byte[] buffer = new byte[1024]; // int size; ServletOutputStream out = null; try { out = response.getOutputStream(); while ((size = stream.read(buffer, 0, buffer.length)) != -1) out.write(buffer, 0, size); } catch (Exception e) { System.out.println(e.toString()); System.out.println("Writing messed up!"); } finally { in.close(); out.flush(); // close() should flush already, but Tomcat 5.5 doesn't out.close(); } }
From source file:com.android.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w w w .j a va 2 s. c o m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); 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(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { 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:org.sakaiproject.portlets.PortletIFrame.java
public boolean popupXFrame(RenderRequest request, Placement placement, String url) { if (xframeCache < 1) return false; // Only check http:// and https:// urls if (!(url.startsWith("http://") || url.startsWith("https://"))) return false; // Check the "Always POPUP" and "Always INLINE" regular expressions String pattern = null;// w w w.ja v a 2 s . c om Pattern p = null; Matcher m = null; pattern = ServerConfigurationService.getString(IFRAME_XFRAME_POPUP, null); if (pattern != null && pattern.length() > 1) { p = Pattern.compile(pattern); m = p.matcher(url.toLowerCase()); if (m.find()) { return true; } } pattern = ServerConfigurationService.getString(IFRAME_XFRAME_INLINE, null); if (pattern != null && pattern.length() > 1) { p = Pattern.compile(pattern); m = p.matcher(url.toLowerCase()); if (m.find()) { return false; } } // Don't check Local URLs String serverUrl = ServerConfigurationService.getServerUrl(); if (url.startsWith(serverUrl)) return false; if (url.startsWith(ServerConfigurationService.getAccessUrl())) return false; // Force http:// to pop-up if we are https:// if (request.isSecure() || (serverUrl != null && serverUrl.startsWith("https://"))) { if (url.startsWith("http://")) return true; } // Check to see if time has expired... Date date = new Date(); long nowTime = date.getTime(); String lastTimeS = placement.getPlacementConfig().getProperty(XFRAME_LAST_TIME); long lastTime = -1; try { lastTime = Long.parseLong(lastTimeS); } catch (NumberFormatException nfe) { lastTime = -1; } M_log.debug("lastTime=" + lastTime + " nowTime=" + nowTime); if (lastTime > 0 && nowTime < lastTime + xframeCache) { String lastXF = placement.getPlacementConfig().getProperty(XFRAME_LAST_STATUS); M_log.debug("Status from placement=" + lastXF); return "true".equals(lastXF); } placement.getPlacementConfig().setProperty(XFRAME_LAST_TIME, String.valueOf(nowTime)); boolean retval = false; try { // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection.setFollowRedirects(true); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); Map headerfields = con.getHeaderFields(); Set headers = headerfields.entrySet(); for (Iterator i = headers.iterator(); i.hasNext();) { Map.Entry map = (Map.Entry) i.next(); String key = (String) map.getKey(); if (key == null) continue; key = key.toLowerCase(); if (!"x-frame-options".equals(key)) continue; // Since the valid entries are SAMEORIGIN, DENY, or ALLOW-URI // we can pretty much assume the answer is "not us" if the header // is present retval = true; break; } } catch (Exception e) { // Fail pretty silently because this could be pretty chatty with bad urls and all M_log.debug(e.getMessage()); retval = false; } placement.getPlacementConfig().setProperty(XFRAME_LAST_STATUS, String.valueOf(retval)); // Permanently set popup to true as we don't expect that a site will go back if (retval == true) placement.getPlacementConfig().setProperty(POPUP, "true"); placement.save(); M_log.debug("Retrieved=" + url + " XFrame=" + retval); return retval; }
From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w w w. j a va 2s.c o m map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode; try { responseCode = connection.getResponseCode(); } catch (IOException e) { // 4.1.x/4.2.x/4.3.x ? (WWW-Authenticate: Basic realm="XXX") // ??401 // java.io.IOException: No authentication challenges found // ?getResponseCode?? responseCode = connection.getResponseCode(); } if (responseCode == -1) { throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, 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) { String value = ""; for (String v : header.getValue()) { value += (v + "; "); } Header h = new BasicHeader(header.getKey(), value); response.addHeader(h); } } return response; }
From source file:ostepu.request.httpRequest.java
/** * fhrt eine benutzerdefinierte Anfrage aus (falls eine besondere * Anfrageform bentigt wird)/* w w w . j ava 2 s.c o m*/ * * @param url die Zieladresse * @param method die Aufrufmethode (sowas wie GET, POST, DELETE) * @param content der Anfrageinhalt * @param auth eine Authentifizierungsmethode (noAuth, httpAuth) * @return das Anfrageresultat */ public static httpRequestResult custom(String url, String method, String content, authentication auth) { URL urlurl; try { urlurl = new URL(url); } catch (MalformedURLException ex) { Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } HttpURLConnection connection; try { connection = (HttpURLConnection) urlurl.openConnection(); } catch (IOException ex) { Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } try { connection.setRequestMethod(method); } catch (ProtocolException ex) { // falsche Methode Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setDefaultUseCaches(false); // connection.setIfModifiedSince(0); // connection.setRequestProperty("Cache-Control","no-cache"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (auth != null) { auth.performAuth(connection); } if (!"".equals(content)) { connection.setRequestProperty("Content-Length", String.valueOf(content.length())); } // fhrt die Anfrage aus OutputStreamWriter writer = null; httpRequestResult Result; try { if (!"".equals(content)) { try { writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(content); writer.flush(); } catch (IOException ex) { Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } } } finally { Result = new httpRequestResult(); try { Result.setStatus(connection.getResponseCode()); } catch (IOException ex) { Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } Result.setHeaders(connection.getHeaderFields()); // Result.setContent((String) connection.getContent()); InputStream stream = connection.getErrorStream(); if (stream == null) { try { stream = connection.getInputStream(); } catch (IOException e) { stream = null; } } if (stream != null) { // This is a try with resources, Java 7+ only // If you use Java 6 or less, use a finally block instead byte[] res; try { res = IOUtils.toByteArray(stream); stream.close(); } catch (IOException ex) { Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } Result.setContent(res); } else { Result.setContent("".getBytes()); } Result.setMethod(method); Result.setUrl(url); } // ab hier wird die Antwort zusammengebaut if (writer != null) { try { writer.close(); } catch (IOException ex) { // der Stream konnte nicht geschlossen werden Logger.getLogger(httpRequest.class.getName()).log(Level.SEVERE, null, ex); return new httpRequestResult(500, new byte[] {}); } } connection.disconnect(); return Result; }