Consumir un Http Form
De Mono Hispano
[editar]
Consumir un Http Form
- Autores: Jonatan Anauati
- E-mail: barakawins@gmail.com
- Lenguajes: C#
- Categorías: Internet, Http Forms, GET, POST, expresiones regulares
- Descripción: Consumir un Form Http usando POST o GET.
- Fecha: 21-08-2008
En el siguiente ejemplo muestro una clase para consumir un form http utilizando POST o GET. Luego muestro dos ejemplos de su aplicación. El primero simplemente la usa para realizar un búsqueda en google. El segundo utiliza la herencia para generar un traductor de texto.
namespace TestHttpRequest
{
using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Collections;
class HttpForm
{
public enum HttpFormMethod : uint
{
POST,
GET
}
HttpFormMethod method;
HttpWebRequest req;
HttpWebResponse resp;
Hashtable fields;
string url=null;
static string EncodeData (string paramName, string value)
{
return "&"+paramName+"="+HttpUtility.UrlEncode (value);
}
public HttpForm (string url, HttpFormMethod method)
{
fields = new Hashtable ();
this.method = method;
this.url = url;
}
public HttpForm AddField (string name, string val)
{
this.fields[name]=val;
return this;
}
public HttpForm RemoveField (string name)
{
try
{
this.fields.Remove(name);
}
catch (Exception ex)
{ }
return this;
}
private object getFieldsData ()
{
StringBuilder encodedData = new StringBuilder ();
foreach (DictionaryEntry de in this.fields)
encodedData.Append (EncodeData (de.Key.ToString(), de.Value.ToString()));
if (this.method == HttpFormMethod.POST)
{
return System.Text.Encoding.Default.GetBytes (encodedData.ToString());
}
return encodedData.ToString();
}
publicvirtualstring Invoke ()
{
Stream postDataWriter= null;
StreamReader reader = null;
string response = null;
try
{
if (this.method == HttpFormMethod.POST)
{
byte [] buffer = (byte[])this.getFieldsData ();
this.req = (HttpWebRequest)WebRequest.Create (url);
this.req.Method = method.ToString ();
this.req.ContentLength = buffer.Length;
postDataWriter = this.req.GetRequestStream ();
postDataWriter.Write (buffer, 0, buffer.Length);
postDataWriter.Close ();
}
else
{
this.req = (HttpWebRequest)WebRequest.Create (url+"?"+this.getFieldsData ().ToString());
}
// obtiene la respuesta
resp = (HttpWebResponse) this.req.GetResponse ();
reader = new StreamReader (resp.GetResponseStream ());
response = reader.ReadToEnd ();
reader.Close ();
resp.Close ();
}
catch (Exception ex)
{
if (reader != null) reader.Close ();
if (resp != null) resp.Close ();
throw ex;
}
return response;
}
}
}
Un Ejemplo Sencillo de su uso con parámetros GET:
public static void Main(string[] args)
{
HttpForm form = new HttpForm ("http://www.google.com.ar/search", HttpForm.HttpFormMethod.GET);
form.AddField ("hl","es");
form.AddField ("q","river+plate");
string ret = form.Invoke ();
System.Console.WriteLine (ret);
}
Un Ejemplo un poco mas complicado, ahora con parámetros POST. En este generamos un traductor de texto utilizando también las bondades de google.
using System;
using System.Text;
using System.Text.RegularExpressions;
class GoogleTranslator
: HttpForm
{
public enum Lang: uint
{
es,en
}
static string url="http://translate.google.com/translate_t?langpair=";
static string ComposeLangPair (Lang fromLang, Lang toLang)
{
return fromLang.ToString()+"|"+toLang.ToString();
}
public GoogleTranslator (Lang fromLang, Lang toLang)
: base (url+ComposeLangPair (fromLang, toLang), HttpFormMethod.POST)
{
this.AddField ("hl","es");
this.AddField ("ie","UTF-8");
this.AddField ("langpair",ComposeLangPair(fromLang, toLang));
}
static string ExtractTranslation (string htmlCode)
{
Regex TradRegex;
Regex TradSubRegex;
Match m;
string str_regex = @".*<div id=result_box dir=""ltr"">(([^<]+(<br>)*)*)</div>.*";
string str_subregex = "[ ]?<br>";
StringBuilder sb = null;
string ret_val = null;
TradRegex = new Regex (str_regex);
TradSubRegex = new Regex (str_subregex);
m = TradRegex.Match (htmlCode);
if (m.Value != string.Empty)
sb = new StringBuilder (m.Groups[1].Value);
if (sb != null)
{
sb.Replace ("<","<");
sb.Replace (">",">");
ret_val = sb.ToString ();
sb = null;
ret_val = TradSubRegex.Replace (ret_val,"\n");
}
return ret_val;
}
public string Translate (string text)
{
string result=null;
this.RemoveField ("text");
this.AddField ("text",text);
result = this.Invoke ();
return ExtractTranslation (result);
}
}
class MainClass
{
public static void Main(string[] args)
{
string result1 = null;
string result2 = "";
string text1="El perro es blanco";
string text2="Este es otro ejemplo";
GoogleTranslator gt = new GoogleTranslator (GoogleTranslator.Lang.es, GoogleTranslator.Lang.en);
result1 = gt.Translate (text1);
result2 = gt.Translate (text2);
System.Console.WriteLine ("{0}: {1}",text1,result1);
System.Console.WriteLine ("{0}: {1}",text2,result2);
}
}
El archivo con todos los ejemplos juntos: EjemploPostGet.cs <<este enlace no funciona>>
para compilar es necesario:
mcs Main.cs -r:System.Web

Powered by MediaWiki