List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:com.nxt.zyl.data.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>(); // chenbo add gzip support,new user-agent if (request.isShouldGzip()) { map.put(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); }/* w w w . j a va2 s .com*/ map.put(USER_AGENT, mUserAgent); // end map.putAll(request.getHeaders()); 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)); } // if (request instanceof MultiPartRequest) { // setConnectionParametersForMultipartRequest(connection, request); // } else { // } 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); } } if (ENCODING_GZIP.equalsIgnoreCase(connection.getContentEncoding())) { response.setEntity(new InflatingEntity(response.getEntity())); } return response; }
From source file:com.example.pabrto.AppEngineClient.java
public static Response getOrPost(Request request) { mErrorMessage = null;// w w w. j a v a 2s . c o m HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); // ... OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": " + e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception { // An OCSP request, ocspTestCert is already created in earlier tests OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber)); OCSPReq req = gen.build();// ww w.j a v a2s. com String reqString = new String(Base64.encode(req.getEncoded(), false)); URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8")); log.debug("OCSP Request: " + url.toExternalForm()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); assertEquals( "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)", 200, con.getResponseCode()); // Some appserver (Weblogic) responds with // "application/ocsp-response; charset=UTF-8" assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus()); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); // Just output the headers to stdout so we can visually inspect them if // something goes wrong Set<String> keys = con.getHeaderFields().keySet(); for (String field : keys) { List<String> values = con.getHeaderFields().get(field); for (String value : values) { log.info(field + ": " + value); } } String eTag = con.getHeaderField("ETag"); assertNotNull( "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)", eTag); assertTrue("ETag is messed up.", ("\"" + new String( Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"") .equals(eTag)); long date = con.getHeaderFieldDate("Date", -1); assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1); long lastModified = con.getHeaderFieldDate("Last-Modified", -1); assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1); // assertTrue("Last-Modified is after response was sent", // lastModified<=date); This will not hold on JBoss AS due to the // caching of the Date-header long expires = con.getExpiration(); assertTrue("Expires is before response was sent", expires >= date); assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0); String cacheControl = con.getHeaderField("Cache-Control"); assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl); assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("public")); assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("no-transform")); assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("must-revalidate")); Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl); assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches()); int maxAge = Integer.parseInt(matcher.group(1)); log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000)); assertTrue( "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)", expires != lastModified); assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.", maxAge < (expires - lastModified) / 1000); // assertTrue("Response cannot be produced after it was sent.", // brep.getProducedAt().getTime() <= date); This might not hold on JBoss // AS due to the caching of the Date-header X509CertificateHolder[] chain = brep.getCerts(); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce)); SingleResp[] singleResps = brep.getResponses(); assertNotNull("SingleResps should not be null.", singleResps); assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1); assertEquals("Serno in response does not match serno in request.", singleResps[0].getCertID().getSerialNumber(), serialNumber); assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null); assertTrue( "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'", singleResps[0].getThisUpdate().getTime() == lastModified); assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'", singleResps[0].getNextUpdate().getTime() == expires); assertTrue("Response cannot be produced before it was last modified..", brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime()); }
From source file:com.android.volley.toolbox.http.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError, IOException { HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from w w w . j a v a2s . c o m map.putAll(additionalHeaders); String url = request.getUrl(); if (mUrlRewriter != null) { url = mUrlRewriter.rewriteUrl(url); if (url == null) { throw new IOException("URL blocked by rewriter: " + url); } } URL parsedUrl = new URL(url); System.err.println(url); HttpURLConnection connection = openConnection(parsedUrl, request); if (!TextUtils.isEmpty(mUserAgent)) { connection.setRequestProperty(HEADER_USER_AGENT, mUserAgent); } 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); 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.iflytek.android.framework.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());/*w w w .j a v a 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()) { VolleyLog.e("======4:" + headerName + ";" + map.get(headerName)); 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:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>GET</code> method. * @param req servlet request/* w w w. j a va 2 s. c o m*/ * @param resp servlet response */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read result headers of GET, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } InputStream in = con.getInputStream(); OutputStream out = resp.getOutputStream(); final byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.flush(); } catch (Exception e) { throw new ServletException(e); } }
From source file:com.hp.mqm.atrf.core.rest.RestConnector.java
/** * @param con that already connected to it's url with an http request, and that should contain a * response for us to retrieve * @return a response from the server to the previously submitted http request * @throws Exception/*from w ww . j a v a 2 s . c om*/ */ private Response retrieveHtmlResponse(HttpURLConnection con) throws IOException { Response ret = new Response(); InputStream inputStream; //select the source of the input bytes, first try "regular" input try { inputStream = con.getInputStream(); } catch (Exception e) { /*if the connection to the server somehow failed, for example 404 or 500, con.getInputStream() will throw an exception, which we'll keep. we'll also store the body of the exception page, in the response data. */ inputStream = con.getErrorStream(); ret.setFailure(e); ret.setResponseData(e.getMessage());//set default error message } //this actually takes the data from the previously decided stream (error or input) and stores it in a byte[] inside the response if (inputStream != null) { ByteArrayOutputStream container = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int read; while ((read = inputStream.read(buf, 0, 1024)) > 0) { container.write(buf, 0, read); } ret.setResponseData(container.toString()); } try { ret.setStatusCode(con.getResponseCode()); } catch (Exception e) { ret.setStatusCode(0); } ret.setResponseHeaders(con.getHeaderFields()); return ret;/**/ }
From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java
@Override public HttpResponse performRequest(final Request<?> request, final Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); final HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w ww.jav a 2 s . co m*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { final String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } final URL parsedUrl = new URL(url); final HttpURLConnection connection = openConnection(parsedUrl, request); for (final String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode; try { // Will throw IOException if server responds with 401. responseCode = connection.getResponseCode(); } catch (final IOException e) { // Will return 401, because now connection has the correct internal // state. 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."); } final StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); final BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (final Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { final Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:de.bps.course.nodes.vc.provider.wimba.WimbaClassroomProvider.java
private String sendRequest(Map<String, String> parameters) { URL url = createRequestUrl(parameters); HttpURLConnection urlConn; try {/*from www . j a va2 s. com*/ urlConn = (HttpURLConnection) url.openConnection(); // setup url connection urlConn.setDoOutput(true); urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(false); // add content type urlConn.setRequestProperty("Content-Type", CONTENT_TYPE); // add cookie information if (cookie != null) urlConn.setRequestProperty("Cookie", cookie); // send request urlConn.connect(); // detect redirect int code = urlConn.getResponseCode(); boolean moved = code == HttpURLConnection.HTTP_MOVED_PERM | code == HttpURLConnection.HTTP_MOVED_TEMP; if (moved) { String location = urlConn.getHeaderField("Location"); List<String> headerVals = urlConn.getHeaderFields().get("Set-Cookie"); for (String val : headerVals) { if (val.startsWith(COOKIE)) cookie = val; } url = createRedirectUrl(location); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Cookie", cookie); } // read response BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = input.readLine()) != null) response.append(line).append("\n"); input.close(); if (isLogDebugEnabled()) logDebug("Response: " + response); return response.toString(); } catch (IOException e) { logError("Sending request to Wimba Classroom failed. Request: " + url.toString(), e); return ""; } }
From source file:jp.go.nict.langrid.commons.protobufrpc.URLRpcChannel.java
public void call(BlockPE<OutputStream, IOException> sender, BlockPE<InputStream, IOException> successReceiver, BlockPPE<InputStream, IOException, IOException> failReceiver) { HttpURLConnection c = null; try {//from w w w .j ava2s . co m c = (HttpURLConnection) url.openConnection(); c.setDoOutput(true); for (Map.Entry<String, String> entry : requestProperties.entrySet()) { c.addRequestProperty(entry.getKey(), entry.getValue()); } if (!requestProperties.containsKey(LangridConstants.HTTPHEADER_PROTOCOL)) { c.addRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.PROTOBUF_RPC); } if (System.getProperty("http.proxyHost") != null) { String proxyAuthUser = System.getProperty("http.proxyUser"); if (proxyAuthUser != null) { String proxyAuthPass = System.getProperty("http.proxyPassword"); String header = proxyAuthUser + ":" + ((proxyAuthPass != null) ? proxyAuthPass : ""); c.setRequestProperty("Proxy-Authorization", "Basic " + new String(Base64.encodeBase64(header.getBytes()))); } } if (authUserName != null && authUserName.length() > 0) { String header = authUserName + ":" + ((authPassword != null) ? authPassword : ""); c.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(header.getBytes()))); } OutputStream os = c.getOutputStream(); try { sender.execute(os); } finally { os.close(); } for (Map.Entry<String, List<String>> entry : c.getHeaderFields().entrySet()) { responseProperties.put(entry.getKey(), StringUtil.join(entry.getValue().toArray(ArrayUtil.emptyStrings()), ", ")); } InputStream is = c.getInputStream(); try { successReceiver.execute(is); } finally { is.close(); } } catch (IOException e) { InputStream es = null; if (c != null) { es = c.getErrorStream(); } try { failReceiver.execute(es, e); } catch (IOException ee) { } finally { if (es != null) { try { es.close(); } catch (IOException ee) { } } } } }