Visual CSharp .NET - desarrollo de API para Rackspace

   
Vista:

desarrollo de API para Rackspace

Publicado por Nery dalhan2006@gmail.com (1 intervención) el 17/02/2012 18:05:33
Buen dia , quisiera solicitarles ayuda pra realizar una API, la cituacion es que ya logre la comunicación, por lo que ya me permite hacer consultas. lo que no logro es como hacer para subir la informacion ya que no se que formato darle a la cadena que se envia en el POST. estoy utilizando c sharp. aqui dejo el código para que le echen un vistazo. Cualquiere ayuda se los agradeceria muchisimo. (alli esta las dos que encontre una es con webclient, y el otro con httprequest). gracias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace rackspaceTest
{
using System;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Text;
using System.Net;

public class clsMetodosWeb
{
private WebClient client;
private string baseUrl;
private string apiKey;
private string secretKey;
public HttpWebRequest req ;

public clsMetodosWeb(WebClient client, string baseUrl, string apiKey, string secretKey)
{
this.client = client;
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.secretKey = secretKey;

}

public virtual string Get(string url)
{
return MakeRemoteCall((client) =>
{
return client.DownloadString(baseUrl + url);
}, "txt");
}

public virtual string Post(string url, NameValueCollection data)
{
return MakeRemoteCall((client) =>
{
var bytes = client.UploadValues(baseUrl + url, "POST", data);
return Encoding.UTF8.GetString(bytes);
},
"text/xml");
}

private void SignMessage()
{
var userAgent = "C# Client Library";
client.Headers["User-Agent"] = userAgent;

var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmss");

var dataToSign = apiKey + userAgent + dateTime + secretKey;
var hash = SHA1.Create();
var signedBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
var signature = Convert.ToBase64String(signedBytes);

client.Headers["X-Api-Signature"] = apiKey + ":" + dateTime + ":" + signature;


}

private void SignMessage2()
{
var userAgent = ".NET Framework Test Client";
req.UserAgent = userAgent;
var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmss");
var dataToSign = apiKey + userAgent + dateTime + secretKey;
var hash = SHA1.Create();
var signedBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
var signature = Convert.ToBase64String(signedBytes);

req.Headers["X-Api-Signature"] = apiKey + ":" + dateTime + ":" + signature;
req.ContentType = "text/xml; encoding='utf-8'";
}
private void AssignFormat(string format)
{

client.Headers["Accept"] = format;
}

private string MakeRemoteCall(Func<WebClient, string> remoteCall, string format)
{
try
{
SignMessage();
AssignFormat(format);
return remoteCall.Invoke(client);
}
catch (WebException e)
{
return e.Source;
throw new Exception(e.Message);
}
}
private void AssignFormat2(string format)
{
//req.Headers.Add("Accept");
req.Accept= format;
}
private string MakeRemoteCall2(string format)
{
try
{
SignMessage();
AssignFormat2(format);
//return remoteCall;
return "bien";
}
catch (WebException e)
{
return e.Source;
throw new Exception(e.Message);
}
}
public virtual string HttpPost(string url, string[] paramName, string[] paramVal)
{

req = WebRequest.Create(new Uri(baseUrl+url)) as HttpWebRequest;
req.Method = "POST";
StringBuilder paramz = new StringBuilder();
for (int i = 0; i < paramName.Length; i++)
{


paramz.Append("'" + paramName[i] + "'");
paramz.Append(" : ");
paramz.Append("'" + HttpUtility.UrlEncode(paramVal[i]) + "'");
paramz.Append(",");

}

// Encode the parameters as form data:
string temp;
temp = "{" + paramz.ToString().Remove(paramz.ToString().Length - 1) + "}";




byte[] formData =
// UTF8Encoding.UTF8.GetBytes(paramz.ToString());


UTF8Encoding.UTF8.GetBytes(temp);

req.ContentLength = formData.Length;

// Send the request:
req.Timeout = 100000;
SignMessage2();
AssignFormat2("text/xml");
using (Stream post = req.GetRequestStream())
{
post.Write(formData, 0, formData.Length);
}

// Pick up the response:
string result = "";
try {
using (var response = req.GetResponse() as HttpWebResponse) {
if (req.HaveResponse && response != null) {
using (var reader = new StreamReader(response.GetResponseStream())) {
result = reader.ReadToEnd();
}
}
}
}
catch (WebException wex) {
if (wex.Response != null) {
using (var errorResponse = (HttpWebResponse)wex.Response) {
using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
string error = reader.ReadToEnd();
//TODO: use JSON.net to parse this string and look at the error message
result = error +" DATA:::"+ temp;
}
}
}
}



return result;
}

}
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder