[Spanish] OpenLayer.ProxyHost

Wladimir Szczerban bolosig at gmail.com
Mon May 7 04:06:45 EDT 2012


Hola Alejandro,

El proxyHost de OL sirve como "puente" para evitar los problemas de cross
domain del navegador. Puedes usar el cgi de python que tiene el OL o
montarte un proxy con php, java, etc.

Este es el proxy.php de mapbuilder.
http://docs.codehaus.org/display/MAP/Downloads

<?php
/*
License: LGPL as per: http://www.gnu.org/copyleft/lesser.html
$Id: proxy.php 3650 2007-11-28 00:26:06Z rdewit $
$Name$
*/

////////////////////////////////////////////////////////////////////////////////
// Description:
// Script to redirect the request http://host/proxy.php?url=http://someUrl
// to http://someUrl .
//
// This script can be used to circumvent javascript's security requirements
// which prevent a URL from an external web site being called.
//
// Author: Nedjo Rogers
////////////////////////////////////////////////////////////////////////////////

// read in the variables

if(array_key_exists('HTTP_SERVERURL', $_SERVER)){
  $onlineresource=$_SERVER['HTTP_SERVERURL'];
}else{
  $onlineresource=$_REQUEST['url'];
}
$parsed = parse_url($onlineresource);
$host = @$parsed["host"];
$path = @$parsed["path"] . "?" . @$parsed["query"];
if(empty($host)) {
  $host = "localhost";
}
$port = @$parsed['port'];
if(empty($port)){
  $port="80";
}
$contenttype = @$_REQUEST['contenttype'];
if(empty($contenttype)) {
  $contenttype = "text/xml";
}
$data = @$GLOBALS["HTTP_RAW_POST_DATA"];
// define content type
header("Content-type: " . $contenttype);

if(empty($data)) {
  $result = send_request();
}
else {
  // post XML
  $posting = new HTTP_Client($host, $port, $data);
  $posting->set_path($path);
  $result = $posting->send_request();
}

// strip leading text from result and output result
$len=strlen($result);
$pos = strpos($result, "<");
if($pos > 1) {
  $result = substr($result, $pos, $len);
}
//$result = str_replace("xlink:","",$result);
echo $result;

// define class with functions to open socket and post XML
// from http://www.phpbuilder.com/annotate/message.php3?id=1013274 by
Richard Hundt

class HTTP_Client {
  var $host;
  var $path;
  var $port;
  var $data;
  var $socket;
  var $errno;
  var $errstr;
  var $timeout;
  var $buf;
  var $result;
  var $agent_name = "MyAgent";
  //Constructor, timeout 30s
  function HTTP_Client($host, $port, $data, $timeout = 30) {
    $this->host = $host;
    $this->port = $port;
    $this->data = $data;
    $this->timeout = $timeout;
  }

  //Opens a connection
  function connect() {
    $this->socket = fsockopen($this->host,
      $this->port,
      $this->errno,
      $this->errstr,
      $this->timeout
      );
    if(!$this->socket)
      return false;
    else
      return true;
  }

  //Set the path
  function set_path($path) {
    $this->path = $path;
  }

  //Send request and clean up
  function send_request() {
    if(!$this->connect()) {
      return false;
    }
    else {
      $this->result = $this->request($this->data);
      return $this->result;
    }
  }

  function request($data) {
    $this->buf = "";
    fwrite($this->socket,
      "POST $this->path HTTP/1.0\r\n".
      "Host:$this->host\r\n".
      "User-Agent: $this->agent_name\r\n".
      "Content-Type: application/xml\r\n".
      "Content-Length: ".strlen($data).
      "\r\n".
      "\r\n".$data.
      "\r\n"
    );

    while(!feof($this->socket))
      $this->buf .= fgets($this->socket, 2048);
      $this->close();
      return $this->buf;
  }


  function close() {
    fclose($this->socket);
  }
}



function send_request() {
  global $onlineresource;
  $ch = curl_init();
  $timeout = 5; // set to zero for no timeout

  // fix to allow HTTPS connections with incorrect certificates
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

  curl_setopt ($ch, CURLOPT_URL,$onlineresource);
  curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  curl_setopt ($ch, CURLOPT_ENCODING , "gzip, deflate");

  $file_contents = curl_exec($ch);
  curl_close($ch);
  $lines = array();
  $lines = explode("\n", $file_contents);
  if(!($response = $lines)) {
    echo "Unable to retrieve file '$service_request'";
  }
  $response = implode("",$response);
  return $response;
}
?>

Este es uno en jsp https://github.com/chrismayer/JSP-Whitelist-Proxy

<%@page session="false"%>
<%@page import="java.net.*,java.io.*" %>
<%@page trimDirectiveWhitespaces="true"%>
<%

/**
 * This is a white list proxy that could be used the prevent an error due to
 * JavaScript Same Origin Policy.
 *
 * CAUTION: It might break some sites and it's a security risk because
 * people can use this proxy to browse the web and possibly do bad
and/or illegal stuff
 * with it.
 * It can load any content type.
 * This proxy implementation was inspired by the proxy.cgi script of OpenLayers
 * {@link http://openlayers.org}
 * To use this in OpenLayers you have to set OpenLayers.ProxyHost =
"Url/To/This/Proxyfile/proxy.jsp?";
 * within your JavaScript code <br>
 * The base code of the proxy has been provided by SNIPPLR
 * {@link http://snipplr.com/view/17987/jsp-proxy-for-javascript-applications/}
 *
 * @author terrestris GmbH & Co. KG
 * @author Christian Mayer
 * @author Marc Jansen
 *
 * @license BSD see license.txt
 *
 */
String[] allowedHosts = {
    "www.openlayers.org", "openlayers.org",
    "labs.metacarta.com", "world.freemap.in",
    "prototype.openmnnd.org", "geo.openplans.org",
    "sigma.openplans.org", "demo.opengeo.org",
    "www.openstreetmap.org", "sample.azavea.com",
    "v-swe.uni-muenster.de:8080",
    "vmap0.tiles.osgeo.org"
};
HttpURLConnection con = null;
try {
	String reqUrl = request.getQueryString();
	String decodedUrl = "";
	if (reqUrl != null) {
		reqUrl = URLDecoder.decode(reqUrl, "UTF-8");
	}
	else {
		response.setStatus(400);
		out.println("ERROR 400: No target specified for proxy.");
	}

	// extract the host
	String host = "";
	host = reqUrl.split("\\/")[2];
	boolean allowed = false;

	// check if host (with port) is in white list
	for (String surl : allowedHosts) {
		if (host.equalsIgnoreCase(surl)) {
			allowed = true;
			break;
		}
	}

	// do the proxy action (load requested ressource and transport it to client)
	// if host is in white list
	if(allowed) {
		// replace the white spaces with plus in URL
		reqUrl = reqUrl.replaceAll(" ", "+");

		// call the requested ressource		
		URL url = new URL(reqUrl);
		con = (HttpURLConnection)url.openConnection();
		con.setDoOutput(true);
		con.setRequestMethod(request.getMethod());
		String reqContenType = request.getContentType();
		if(reqContenType != null) {
			con.setRequestProperty("Content-Type", reqContenType);
		}
		else {
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		}

		int clength = request.getContentLength();
		if(clength > 0) {
			con.setDoInput(true);
			byte[] idata = new byte[clength];
			request.getInputStream().read(idata, 0, clength);
			con.getOutputStream().write(idata, 0, clength);	
		}

		// respond to client
		response.setContentType(con.getContentType());

		BufferedReader rd = new BufferedReader(new
InputStreamReader(con.getInputStream()));
		String line;
		int i = 0;
		while ((line = rd.readLine()) != null) {
			out.println(line);	
		}
		rd.close();
	}
	else {
		// deny access via HTTP status code 502
		response.setStatus(502);
		out.println("ERROR 502: This proxy does not allow you to access that
location.");
	}

} catch(Exception e) {

	// resond an internal server error with the stacktrace
	// on exception
	response.setStatus(500);
	byte[] idata = new byte[5000];

	if(con.getErrorStream() != null) {
		con.getErrorStream().read(idata, 0, 5000);
	}

	out.println("ERROR 500: An internal server error occured. " +
e.getMessage() + " " + new String(idata));
}
%>


Saludos,

Bolo


El 19 de abril de 2012 00:52, J.Alejandro Martinez Linares <
islanis en infomed.sld.cu> escribió:

> Hola gente alguien pudiera explicarme o mandarme alguna documentación
> sobre OpenLayer.ProxyHost, es que no es que es y no tengo internet pero
> ademas sin eso no puedo sacar info a traves de mis capas WMS , no me salen
> ni siquiera los mismos cortos que cojo de geoserver que como son de
> openlayer pero no me funcionan hay algo que no me deja verlo de forma
> corrrecto y si no defino un OpenLayer.ProxyHost me da el siguiente error
>
> You probably need to set OpenLayers.ProxyHost to access ${url}.See
> http://trac.osgeo.org/**openlayers/wiki/**FrequentlyAskedQuestions#**
> ProxyHost<http://trac.osgeo.org/openlayers/wiki/FrequentlyAskedQuestions#ProxyHost>
>
> --
>
> Este mensaje le ha llegado mediante el servicio de correo electronico que
> ofrece Infomed para respaldar el cumplimiento de las misiones del Sistema
> Nacional de Salud. La persona que envia este correo asume el compromiso de
> usar el servicio a tales fines y cumplir con las regulaciones establecidas
>
> Infomed: http://www.sld.cu/
> ______________________________**_________________
> Spanish mailing list
> http://lists.osgeo.org/**mailman/listinfo/spanish<http://lists.osgeo.org/mailman/listinfo/spanish>
> http://es.osgeo.org
> http://twitter.com/osgeoes
>



-- 
Saludos,

Bolo
www.geoinquiets.cat
------------ próxima parte ------------
Se ha borrado un adjunto en formato HTML...
URL: http://lists.osgeo.org/pipermail/spanish/attachments/20120507/5b73542f/attachment-0001.html


More information about the Spanish mailing list