List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:org.myframe.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 ww w . j ava 2 s.co 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 = 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:org.kymjs.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>(); //just marker by chenlin map.putAll(request.getHeaders());//from ww 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 = 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:org.jboss.aerogear.android.pipe.http.HttpRestProvider.java
private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException { int statusCode = urlConnection.getResponseCode(); HeaderAndBody result;/* w w w .java2s . co m*/ Map<String, List<String>> headers; byte[] responseData; switch (statusCode) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: InputStream in = new BufferedInputStream(urlConnection.getInputStream()); responseData = readBytes(in); break; case HttpStatus.SC_NO_CONTENT: responseData = new byte[0]; break; default: InputStream err = new BufferedInputStream(urlConnection.getErrorStream()); byte[] errData = readBytes(err); Map<String, List<String>> errorListHeaders = urlConnection.getHeaderFields(); Map<String, String> errorHeaders = new HashMap<String, String>(); for (String header : errorListHeaders.keySet()) { String comma = ""; StringBuilder errorHeaderBuilder = new StringBuilder(); for (String errorHeader : errorListHeaders.get(header)) { errorHeaderBuilder.append(comma).append(errorHeader); comma = ","; } errorHeaders.put(header, errorHeaderBuilder.toString()); } throw new HttpException(errData, statusCode, errorHeaders); } headers = urlConnection.getHeaderFields(); result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size())); for (Map.Entry<String, List<String>> header : headers.entrySet()) { result.setHeader(header.getKey(), TextUtils.join(",", header.getValue())); } return result; }
From source file:org.apache.niolex.commons.net.HTTPUtil.java
/** * Do the HTTP request.//ww w . j a v a 2s .c o m * * @param strUrl the request URL * @param params the request parameters * @param paramCharset the charset used to send the request parameters * @param headers the request headers * @param connectTimeout the connection timeout * @param readTimeout the data read timeout * @param useGet whether do we use the HTTP GET method * @return the response pair; a is response header map, b is response body * @throws NetException */ public static final Pair<Map<String, List<String>>, byte[]> doHTTP(String strUrl, Map<String, String> params, String paramCharset, Map<String, String> headers, int connectTimeout, int readTimeout, boolean useGet) throws NetException { LOG.debug("Start HTTP {} request to [{}], C{}R{}.", useGet ? "GET" : "POST", strUrl, connectTimeout, readTimeout); InputStream in = null; try { // 1. For get, we pass parameters in URL; for post, we save it in reqBytes. byte[] reqBytes = null; if (!CollectionUtil.isEmpty(params)) { if (useGet) { strUrl = strUrl + '?' + prepareWwwFormUrlEncoded(params, paramCharset); } else { reqBytes = StringUtil.strToAsciiByte(prepareWwwFormUrlEncoded(params, paramCharset)); } } URL url = new URL(strUrl); // We use Java URL to do the HTTP request. URLConnection ucon = url.openConnection(); ucon.setConnectTimeout(connectTimeout); ucon.setReadTimeout(readTimeout); // 2. validate to Connection type. if (!(ucon instanceof HttpURLConnection)) { throw new NetException(NetException.ExCode.INVALID_URL_TYPE, "The request is not in HTTP protocol."); } final HttpURLConnection httpCon = (HttpURLConnection) ucon; // 3. We add all the request headers. if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpCon.addRequestProperty(entry.getKey(), entry.getValue()); } } // 4. For get or no parameter, we do not output data; for post, we pass parameters in Body. if (reqBytes == null) { httpCon.setDoOutput(false); } else { httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpCon.setRequestProperty("Content-Length", Integer.toString(reqBytes.length)); httpCon.setRequestMethod("POST"); httpCon.setDoOutput(true); } httpCon.setDoInput(true); httpCon.connect(); // 5. do output if needed. if (reqBytes != null) { StreamUtil.writeAndClose(httpCon.getOutputStream(), reqBytes); } // 6. Get the input stream. in = httpCon.getInputStream(); final int contentLength = httpCon.getContentLength(); validateHttpCode(strUrl, httpCon); byte[] ret = null; // 7. Read response byte array according to the strategy. if (contentLength > 0) { ret = commonDownload(contentLength, in); } else { ret = unusualDownload(strUrl, in, MAX_BODY_SIZE, true); } // 8. Parse the response headers. LOG.debug("Succeeded to execute HTTP request to [{}], response size {}.", strUrl, ret.length); return Pair.create(httpCon.getHeaderFields(), ret); } catch (NetException e) { LOG.info(e.getMessage()); throw e; } catch (Exception e) { String msg = "Failed to execute HTTP request to [" + strUrl + "], msg=" + e.toString(); LOG.warn(msg); throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e); } finally { // Close the input stream. StreamUtil.closeStream(in); } }
From source file:test.ShopThreadSrc.java
private boolean doPTShop() throws Exception { LogUtil.infoPrintf("?----------->"); //loadCookie(); boolean result = true; String postParams = addPTDynamicParams(); 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);/*from w w w .ja 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.infoPrintf("?----------->"); } else { LogUtil.infoPrintf("??----------->"); LogUtil.debugPrintf("cookie====" + cookie); setCookies(cookie); } LogUtil.infoPrintf("??----------->"); //System.out.println(list.toHtml()); return result; }
From source file:org.devnexus.aerogear.HttpRestProvider.java
private HeaderAndBody getHeaderAndBody(HttpURLConnection urlConnection) throws IOException { int statusCode = urlConnection.getResponseCode(); HeaderAndBody result;/*from w w w . j a v a2s.com*/ Map<String, List<String>> headers; byte[] responseData; switch (statusCode) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: InputStream in = new BufferedInputStream(urlConnection.getInputStream()); responseData = readBytes(in); break; case HttpStatus.SC_NO_CONTENT: responseData = new byte[0]; break; default: InputStream err = new BufferedInputStream(urlConnection.getErrorStream()); byte[] errData = readBytes(err); Map<String, String> errorHeaders = Maps.transformValues(urlConnection.getHeaderFields(), new Function<List<String>, String>() { @Override public String apply(List<String> input) { return TextUtils.join(",", input); } }); throw new HttpException(errData, statusCode, errorHeaders); } headers = urlConnection.getHeaderFields(); result = new HeaderAndBody(responseData, new HashMap<String, Object>(headers.size())); for (Map.Entry<String, List<String>> header : headers.entrySet()) { result.setHeader(header.getKey(), TextUtils.join(",", header.getValue())); } return result; }
From source file:de.thingweb.discovery.TDRepository.java
/** * Adds a ThingDescription to Repository * //from w ww . j ava 2 s . c o m * @param content JSON-LD * @return key of entry in repository * @throws Exception in case of error */ public String addTD(byte[] content) throws Exception { URL url = new URL("http://" + repository_uri + "/td"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("content-type", "application/ld+json"); httpCon.setRequestMethod("POST"); OutputStream out = httpCon.getOutputStream(); out.write(content); out.close(); InputStream is = httpCon.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } int responseCode = httpCon.getResponseCode(); httpCon.disconnect(); String key = ""; // new String(baos.toByteArray()); if (responseCode != 201) { // error throw new RuntimeException("ResponseCodeError: " + responseCode); } else { Map<String, List<String>> hf = httpCon.getHeaderFields(); List<String> los = hf.get("Location"); if (los != null && los.size() > 0) { key = los.get(0); } } return key; }
From source file:org.wso2.carbon.esb.mediator.test.iterate.IterateJsonPathTest.java
private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws AutomationFrameworkException, IOException { HttpURLConnection urlConnection = null; try {/* w w w .j av a2 s. c o m*/ urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("POST"); } catch (ProtocolException e) { throw new AutomationFrameworkException( "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); urlConnection.setReadTimeout(10000); for (Map.Entry<String, String> e : headers.entrySet()) { urlConnection.setRequestProperty(e.getKey(), e.getValue()); } OutputStream out = urlConnection.getOutputStream(); Writer writer = null; try { writer = new OutputStreamWriter(out, "UTF-8"); writer.write(postBody); } catch (IOException e) { throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e); } finally { if (writer != null) { writer.close(); } } StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Object responseHeaders = new HashMap(); String key; while (itr.hasNext()) { key = itr.next(); if (key != null) { ((Map) responseHeaders).put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), (Map) responseHeaders); } catch (IOException e) { StringBuilder sb = new StringBuilder(); BufferedReader rd = null; rd = new BufferedReader( new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); return new HttpResponse(sb.toString(), urlConnection.getResponseCode()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }
From source file:com.aylien.textapi.HttpSender.java
public String post(String url, Map<String, String> parameters, Map<String, String> headers) throws IOException, TextAPIException { try {/*from w w w . j a v a2 s. co m*/ HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); for (Map.Entry<String, String> header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", USER_AGENT); StringBuilder payload = new StringBuilder(); for (Map.Entry<String, String> e : parameters.entrySet()) { if (payload.length() > 0) { payload.append('&'); } payload.append(URLEncoder.encode(e.getKey(), "UTF-8")).append('=') .append(URLEncoder.encode(e.getValue(), "UTF-8")); } OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(payload.toString()); writer.close(); responseHeaders = connection.getHeaderFields(); InputStream inputStream = connection.getResponseCode() == 200 ? connection.getInputStream() : connection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); if (connection.getResponseCode() >= 300) { extractTextAPIError(response.toString()); } return response.toString(); } catch (MalformedURLException e) { throw new IOException(e); } }
From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java
public TequilaToken getTequilaTokenForMoodle() throws TException { System.out.println("getTequilaTokenForMoodle"); try {//www . ja v a2 s.com HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php") .openConnection(); conn2.setInstanceFollowRedirects(false); conn2.getInputStream(); URL url = new URL(conn2.getHeaderField("Location")); MultiMap<String> params = new MultiMap<String>(); UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8"); TequilaToken teqToken = new TequilaToken(params.getString("requestkey")); Cookie cookie = new Cookie(); for (String header : conn2.getHeaderFields().get("Set-Cookie")) { cookie.addFromHeader(header); } teqToken.setLoginCookie(cookie.cookie()); return teqToken; } catch (IOException e) { e.printStackTrace(); throw new TException("Failed to getTequilaToken from upstream server"); } }