Pregunta

Ahora he estado tratando de utilizar Launchpad's API para escribir un pequeño envoltorio sobre ella usando C # .NET o Mono. Según OAuth, lo primero que necesita para obtener las peticiones firmadas y Launchpad tiene su propia forma de hacerlo .

Lo que tengo que hacer es crear una conexión con https://edge.launchpad.net / + solicitud de token con algún necesaria encabezados HTTP como Content-type. En Python tengo urllib2, pero al mirar en el espacio de nombres System.Net, que sopló mi cabeza. Yo no era capaz de entender cómo empezar con ella. Hay mucha confusión si puedo usar WebRequest, HttpWebRequest o WebClient. Con WebClient Incluso recibo errores de certificado, ya que, no se añaden como los de confianza.

A partir de las API de Google Docs, se dice que tres teclas tienen que enviarse a través de POST

  • auth_consumer_key: Su clave de los consumidores
  • oauth_signature_method: La cadena "TEXTO SIMPLE"
  • oauth_signature: La cadena "&".

Así que la petición HTTP podría tener este aspecto:

POST /+request-token HTTP/1.1
Host: edge.launchpad.net
Content-type: application/x-www-form-urlencoded

oauth_consumer_key=just+testing&oauth_signature_method=PLAINTEXT&oauth_signature=%26

La respuesta debe ser algo como esto:

200 OK

oauth_token=9kDgVhXlcVn52HGgCWxq&oauth_token_secret=jMth55Zn3pbkPGNht450XHNcHVGTJm9Cqf5ww5HlfxfhEEPKFflMqCXHNVWnj2sWgdPjqDJNRDFlt92f

he cambiado de código muchas veces y, finalmente, todo lo que puedo conseguir algo así como

HttpWebRequest clnt = HttpWebRequest.Create(baseAddress) as HttpWebRequest;
// Set the content type
clnt.ContentType =  "application/x-www-form-urlencoded";
clnt.Method = "POST";

string[] listOfData ={
    "oauth_consumer_key="+oauth_consumer_key, 
    "oauth_signature="+oauth_signature, 
    "oauth_signature_method"+oauth_signature_method
};

string postData = string.Join("&",listOfData);
byte[] dataBytes= Encoding.ASCII.GetBytes(postData);

Stream newStream = clnt.GetRequestStream();
newStream.Write(dataBytes,0,dataBytes.Length);

¿Cómo procedo más? ¿Debo hacer una llamada de lectura en clnt?

¿Por qué no pueden los desarrolladores .NET hacer una clase que podemos utilizar para leer y escribir en lugar de crear cientos de clases y confundiendo todos los recién llegados.

¿Fue útil?

Solución

No, es necesario para cerrar el flujo de solicitud antes de obtener la secuencia de respuesta.
Algo como esto:

Stream s= null;
try
{
    s = clnt.GetRequestStream();
    s.Write(dataBytes, 0, dataBytes.Length);
    s.Close();

    // get the response
    try
    {
        HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
        if (resp == null) return null;

        // expected response is a 200 
        if ((int)(resp.StatusCode) != 200)
            throw new Exception(String.Format("unexpected status code ({0})", resp.StatusCode));
        for(int i=0; i < resp.Headers.Count; ++i)  
                ;  //whatever

        var MyStreamReader = new System.IO.StreamReader(resp.GetResponseStream());
        string fullResponse = MyStreamReader.ReadToEnd().Trim();
    }
    catch (Exception ex1)
    {
        // handle 404, 503, etc...here
    }
}    
catch 
{
}

Pero si usted no necesita todo el control, se puede hacer una solicitud de cliente Web más simple.

string address = "https://edge.launchpad.net/+request-token";
string data = "oauth_consumer_key=just+testing&oauth_signature_method=....";
string reply = null;
using (WebClient client = new WebClient ())
{
  client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
  reply = client.UploadString (address, data);
}

código de trabajo completo (compilación de .NET v3.5):

using System;
using System.Net;
using System.Collections.Generic;
using System.Reflection;

// to allow fast ngen
[assembly: AssemblyTitle("launchpad.cs")]
[assembly: AssemblyDescription("insert purpose here")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright © Dino Chiesa 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.1.1")]

namespace Cheeso.ToolsAndTests
{
    public class launchpad
    {
        public void Run()
        {
            // see http://tinyurl.com/yfkhwkq
            string address = "https://edge.launchpad.net/+request-token";

            string oauth_consumer_key = "stackoverflow1";
            string oauth_signature_method = "PLAINTEXT";
            string oauth_signature = "%26";

            string[] listOfData ={
                "oauth_consumer_key="+oauth_consumer_key,
                "oauth_signature_method="+oauth_signature_method,
                "oauth_signature="+oauth_signature
            };

            string data = String.Join("&",listOfData);

            string reply = null;
            using (WebClient client = new WebClient ())
            {
                client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
                reply = client.UploadString (address, data);
            }

            System.Console.WriteLine("response: {0}", reply);
        }

        public static void Usage()
        {
            Console.WriteLine("\nlaunchpad: request token from launchpad.net\n");
            Console.WriteLine("Usage:\n  launchpad");
        }


        public static void Main(string[] args)
        {
            try
            {
                new launchpad()
                    .Run();
            }
            catch (System.Exception exc1)
            {
                Console.WriteLine("Exception: {0}", exc1.ToString());
                Usage();
            }
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top