如何使用webRequest Class

时间:2018-04-11 13:01:20

标签: c# curl httpclient lob

我正在尝试使用CURL从LOB.com帐户获取明信片信息。

lob.com他们提供:

curl https://api.lob.com/v1/postcards/psc_5c002b86ce47537a \
  -u test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc:

如何使用此CURL获取json响应?

我用过

var httpWebRequest = (HttpWebRequest) WebRequest.Create("https://api.lob.com/v1/postcards/psc_95d1eafeb5b9a766");

httpWebRequest.ContentType = "application/json";

httpWebRequest.Accept = "*/*";

httpWebRequest.Method = "GET";

httpWebRequest.Headers.Add("Authorization", "test_48d2bbf75c2edc75155c401d119bfae5526:");

var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();

using(var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
 gta_allCustomersResponse answer = JsonConvert.DeserializeObject < gta_allCustomersResponse > (streamReader.ReadToEnd());
 return answer;

如果我运行此代码,上面的代码显示422(不可处理的实体)或400(错误的请求)错误。

1 个答案:

答案 0 :(得分:0)

我建议使用RestSharp向Lob发送简单的HTTP请求。

或者您可以使用HttpClient创建它:

public static void Main()
{
    string API_KEY = "YourApiKey";

    HttpClient httpClient = new HttpClient();
    var authHeaderBytes = Encoding.ASCII.GetBytes(API_KEY + ":");
    httpClient.DefaultRequestHeaders.Authorization = 
        new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authHeaderBytes));

    var requestPayload = new Dictionary<string, string>
    {
        { "name", "John Doe" },
        { "address_line1", "123 Main St" },
        { "address_city", "San Francisco" },
        { "address_state", "CA" },
        { "address_zip", "94107" },
        { "address_country", "US" }
    };

    var encodedRequestForm = new FormUrlEncodedContent(requestPayload);
    var APIResponse = httpClient.PostAsync("https://api.lob.com/v1/addresses", encodedRequestForm).GetAwaiter().GetResult();
    var addressString = APIResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();

    System.Console.WriteLine(addressString);
}

此示例用于地址,您可以为明信片开发相同的内容,只需相应地查看文档和代码中的curl请求或Java请求。

希望这有帮助!