List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:servlet.GetCity.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* www. j a va2s.co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public String getData(String urlString) { String result = ""; BufferedReader read = null; try { URL realurl = new URL(urlString); URLConnection connection = realurl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; while ((line = read.readLine()) != null) { result += line; } } catch (IOException e) { e.printStackTrace(); } finally { if (read != null) { try { read.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; }
From source file:info.joseluismartin.gtc.mvc.CacheController.java
private URLConnection getConnection(URL url) throws IOException { URLConnection conn = url.openConnection(proxy); conn.setRequestProperty("User-Agent", USER_AGENT); return conn;/* w w w . ja va 2 s . co m*/ }
From source file:org.apache.jcs.auxiliary.lateral.http.broadcast.LateralCacheThread.java
/** Description of the Method */ public void writeObj(URLConnection connection, ICacheElement cb) { try {//from w w w. j a va2 s . c o m connection.setUseCaches(false); connection.setRequestProperty("CONTENT_TYPE", "application/octet-stream"); connection.setDoOutput(true); connection.setDoInput(true); ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream()); log.debug("os = " + os); // Write the ICacheItem to the ObjectOutputStream log.debug("Writing ICacheItem."); os.writeObject(cb); os.flush(); log.debug("closing output stream"); os.close(); } catch (IOException e) { log.error(e); } // end catch }
From source file:org.n52.wps.server.request.strategy.WCS111XMLEmbeddedBase64OutputReferenceStrategy.java
@Override public ReferenceInputStream fetchData(InputType input) throws ExceptionReport { String dataURLString = input.getReference().getHref(); String schema = input.getReference().getSchema(); String encoding = input.getReference().getEncoding(); String mimeType = input.getReference().getMimeType(); try {/*from w w w . j a v a2 s. c o m*/ URL dataURL = new URL(dataURLString); // Do not give a direct inputstream. // The XML handlers cannot handle slow connections URLConnection conn = dataURL.openConnection(); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setRequestProperty("Content-type", "multipart/mixed"); //Handling POST with referenced document if (input.getReference().isSetBodyReference()) { String bodyReference = input.getReference().getBodyReference().getHref(); URL bodyReferenceURL = new URL(bodyReference); URLConnection bodyReferenceConn = bodyReferenceURL.openConnection(); bodyReferenceConn.setRequestProperty("Accept-Encoding", "gzip"); InputStream referenceInputStream = retrievingZippedContent(bodyReferenceConn); IOUtils.copy(referenceInputStream, conn.getOutputStream()); } //Handling POST with inline message else if (input.getReference().isSetBody()) { conn.setDoOutput(true); input.getReference().getBody().save(conn.getOutputStream()); } InputStream inputStream = retrievingZippedContent(conn); BufferedReader bRead = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; //boundary between different content types String boundary = ""; boolean boundaryFound = false; boolean encodedImagepart = false; String encodedImage = ""; //e.g. base64 String contentTransferEncoding = ""; String imageContentType = ""; int boundaryCount = 0; while ((line = bRead.readLine()) != null) { if (line.contains("boundary")) { boundary = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\"")); boundaryFound = true; continue; } if (boundaryFound) { if (line.contains(boundary)) { boundaryCount++; continue; } } if (encodedImagepart) { encodedImage = encodedImage.concat(line); } //is the image always the third part?! else if (boundaryCount == 2) { if (line.contains("Content-Type")) { imageContentType = line.substring(line.indexOf(":") + 1).trim(); } else if (line.contains("Content-Transfer-Encoding")) { contentTransferEncoding = line.substring(line.indexOf(":") + 1).trim(); } else if (line.contains("Content-ID")) { /* just move further one line (which is hopefully empty) * and start parsing the encoded image */ line = bRead.readLine(); encodedImagepart = true; } } } return new ReferenceInputStream( new Base64InputStream(new ByteArrayInputStream(encodedImage.getBytes())), imageContentType, null); // encoding is null since encoding was removed } catch (RuntimeException e) { throw new ExceptionReport("Error occured while parsing XML", ExceptionReport.NO_APPLICABLE_CODE, e); } catch (MalformedURLException e) { String inputID = input.getIdentifier().getStringValue(); throw new ExceptionReport( "The inputURL of the execute is wrong: inputID: " + inputID + " | dataURL: " + dataURLString, ExceptionReport.INVALID_PARAMETER_VALUE); } catch (IOException e) { String inputID = input.getIdentifier().getStringValue(); throw new ExceptionReport("Error occured while receiving the complexReferenceURL: inputID: " + inputID + " | dataURL: " + dataURLString, ExceptionReport.INVALID_PARAMETER_VALUE); } }
From source file:TSAClient.java
private byte[] getTSAResponse(byte[] request) throws IOException { LOG.debug("Opening connection to TSA server"); // todo: support proxy servers URLConnection connection = url.openConnection(); connection.setDoOutput(true);//www .j av a 2 s. c o m connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/timestamp-query"); LOG.debug("Established connection to TSA server"); if (username != null && password != null && !username.isEmpty() && !password.isEmpty()) { connection.setRequestProperty(username, password); } // read response OutputStream output = null; try { output = connection.getOutputStream(); output.write(request); } finally { IOUtils.closeQuietly(output); } LOG.debug("Waiting for response from TSA server"); InputStream input = null; byte[] response; try { input = connection.getInputStream(); response = IOUtils.toByteArray(input); } finally { IOUtils.closeQuietly(input); } LOG.debug("Received response from TSA server"); return response; }
From source file:es.prodevelop.gvsig.mini.tasks.yours.YOURSFunctionality.java
@Override public boolean execute() { try {//from w ww. j a v a 2s . c o m final Point ini = (Point) route.getStartPoint().clone(); final Point end = (Point) route.getEndPoint().clone(); final String routeString = route.toYOURS(ini, end); log.log(Level.FINE, routeString); /* Define the URL we want to load data from. */ URL parseURL = new URL(routeString); /* Open a connection to that URL. */ if (this.isCanceled()) { res = TaskHandler.CANCELED; return true; } URLConnection urlconnec = parseURL.openConnection(); urlconnec.setRequestProperty("X-Yours-client", "gvSIG"); urlconnec.setReadTimeout(30000); /* Define InputStreams to read from the URLConnection. */ InputStream is = urlconnec.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); /* * Read bytes to the Buffer until there is nothing more to read(-1). */ ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { if (isCanceled()) { res = TaskHandler.CANCELED; return true; } baf.append((byte) current); } res = route.fromYOURS(baf.toByteArray()); } catch (IOException e) { res = TaskHandler.NO_RESPONSE; } catch (Exception e) { res = TaskHandler.ERROR; log.log(Level.SEVERE, "", e); } finally { // handler.sendEmptyMessage(map.ROUTE_SUCCEEDED); try { // if (res == -1) { // handler.sendEmptyMessage(map.ROUTE_CANCELED); if (res == -2) { res = TaskHandler.NO_RESPONSE; } else if (res == -3) { res = TaskHandler.BAD_RESPONSE; } else if (res == 1) { res = TaskHandler.FINISHED; if (route.getState() == Tags.ROUTE_WITH_START_AND_PASS_POINT) { route.setState(Tags.ROUTE_WITH_N_POINT); } else if (route.getState() == Tags.ROUTE_WITH_START_POINT) { route.setState(Tags.ROUTE_WITH_2_POINT); } } } catch (Exception e) { log.log(Level.SEVERE, "", e); } finally { // super.stop(); } return true; } }
From source file:org.apache.ace.connectionfactory.impl.ConnectionFactoryImpl.java
/** * Applies basic authentication to the given connection, if it is a {@link HttpURLConnection}. * //w w w.j a v a 2 s.co m * @param conn * the connection to apply basic authentication to; * @param values * the credentials to apply. */ private void applyBasicAuthentication(URLConnection conn, Object[] values) { if (conn instanceof HttpURLConnection) { conn.setRequestProperty(HTTP_HEADER_AUTHORIZATION, getBasicAuthCredentials(values)); } }
From source file:org.openmrs.module.ModuleUtil.java
/** * Downloads the contents of a URL and copies them to a string (Borrowed from oreilly) * * @param url/* w w w . j ava2s . c o m*/ * @return InputStream of contents * @should return a valid input stream for old module urls */ public static InputStream getURLStream(URL url) { InputStream in = null; try { URLConnection uc = url.openConnection(); uc.setDefaultUseCaches(false); uc.setUseCaches(false); uc.setRequestProperty("Cache-Control", "max-age=0,no-cache"); uc.setRequestProperty("Pragma", "no-cache"); log.debug("Logging an attempt to connect to: " + url); in = openConnectionCheckRedirects(uc); } catch (IOException io) { log.warn("io while reading: " + url, io); } return in; }
From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java
public String getAuthToken(String apiEndPoint, String encodedCliAndSecret) { //receives : apiEndPoint (https://api.test.sabre.com) //encodedCliAndSecret : base64Encode( base64Encode(V1:[user]:[group]:[domain]) + ":" + base64Encode([secret]) ) String strRet = null;//from w w w . ja va2s . c o m try { URL urlConn = new URL(apiEndPoint + "/v1/auth/token"); URLConnection conn = urlConn.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Authorization", "Basic " + encodedCliAndSecret); conn.setRequestProperty("Accept", "application/json"); //send request DataOutputStream dataOut = new DataOutputStream(conn.getOutputStream()); dataOut.writeBytes("grant_type=client_credentials"); dataOut.flush(); dataOut.close(); //get response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strChunk = ""; StringBuilder sb = new StringBuilder(); while (null != ((strChunk = rd.readLine()))) sb.append(strChunk); //parse the token JSONObject respParser = new JSONObject(sb.toString()); strRet = respParser.getString("access_token"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return strRet; }
From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRServerImpl.java
public ResponseType requestCall(RequestType request) { AutoCreate ac = new AutoCreate(); ac.setRequest(request);/*from www .j a v a2 s.co m*/ ResponseType response = null; try { Marshaller marshaller = jaxbc.createMarshaller(); Unmarshaller unmarshaller = jaxbc.createUnmarshaller(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); marshaller.marshal(ac, byteStream); String xml = byteStream.toString(); URL url = new URL(this.serverURL); URLConnection con = url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setRequestProperty("Content-Type", "text/xml"); con.setRequestProperty("Content-transfer-encoding", "text"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); log.info("Sending request: " + xml); out.write(xml); out.flush(); out.close(); InputStream in = con.getInputStream(); int len = 4096; byte[] buffer = new byte[len]; int off = 0; int read = 0; while ((read = in.read(buffer, off, len)) != -1) { off += read; len -= off; } String responseText = new String(buffer, 0, off); log.debug("Received response: " + responseText); Object o = unmarshaller.unmarshal(new ByteArrayInputStream(responseText.getBytes())); if (o instanceof AutoCreate) { AutoCreate acr = (AutoCreate) o; response = acr.getResponse(); } } catch (MalformedURLException e) { log.error("", e); } catch (IOException e) { log.error("", e); } catch (JAXBException e) { log.error("", e); } finally { if (response == null) { response = new ResponseType(); response.setStatus(StatusType.ERROR); response.setErrorCode(ErrorCodeType.MOTECH_UNKNOWN_ERROR); response.setErrorString("Unknown error occurred sending request to IVR server"); } } return response; }