使用以下命令:
curl -v -X GET -H "Content-Type: application/json" -d {'"mode":"0"'} http://host.domain.abc.com:23423/api/start-trial-api/
我能够将JSON数据发送到Web请求并获取响应。 我怎样才能在C#中做同样的事情?
我能够将数据发布到其他服务并获得响应,但不了解如何将数据发送到GET请求。 我尝试在谷歌和stackoverflow上搜索相同的C#,但没有找到任何东西。
答案 0 :(得分:0)
示例代码 - 确保请求方法设置为" GET"
string url = "";
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
var webResponse = request.GetResponse();
using (var s = webResponse.GetResponseStream())
{
using (TextReader textReader = new StreamReader(s, true))
{
string jsonString = textReader.ReadToEnd();
}
}
答案 1 :(得分:0)
此处有很多abstractions
,但希望能在C#
界面
public interface IShopifyAPIGateway
{
HttpResponseMessage Get(string path);
}
Shopify API网关,instatiates
HTTPClient()
public sealed class ShopifyAPIGateway : IShopifyAPIGateway
{
/// <summary>
///
/// </summary>
private Identity _identity;
/// <summary>
///
/// </summary>
private HttpClient _httpClient;
/// <summary>
///
/// </summary>
public ShopifyAPIGateway(Identity
identity)
{
_identity = identity;
_httpClient = new HttpClient(ClientHandler());
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public HttpResponseMessage Get(string path)
{
try
{
var response = Connect().GetAsync(path).Result;
return response;
}
catch (CustomHttpResponseException ex)
{
new Email().SendEmail(_identity.ClientName, "Http Response Error - Shopify API Module",
"Http Response Error - Shopify API Module: " + ex.Message,
"error@retain.me");
throw new CustomHttpResponseException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private HttpClient Connect()
{
try
{
_httpClient.BaseAddress = new Uri(_identity.APIURL);
return _httpClient;
}
catch (CustomHttpRequestException ex)
{
throw new CustomHttpRequestException(ex.Message);
}
}
/// <summary>
///
/// </summary>
/// <param name="userKey"></param>
/// <returns></returns>
private HttpClientHandler ClientHandler()
{
try
{
return new HttpClientHandler()
{
Credentials = new NetworkCredential(_identity.APIKey,
_identity.Password),
PreAuthenticate = true
};
}
catch (CustomClientHandlerException ex)
{
throw new CustomClientHandlerException(ex.Message);
}
}
}
通用存储库返回响应对象与object(s)
匹配的任何T
public sealed class EntityRepository<T> : IEntityRepository<T>
{
private IShopifyAPIGateway _gateWay;
public T Find(string path)
{
try
{
_gateWay = new ShopifyAPIGateway(_identity);
var json = _gateWay.Get(path).Content.ReadAsStringAsync();
T results = JsonConvert.DeserializeObject<T>(json.Result);
return results;
}
catch (System.Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
}
使用返回类型必须与您传递的Type
相匹配,并且还必须与响应中返回的类型相匹配。
private IEnumerable<Order> Orders()
{
var entityRepo = new EntityRepository<Order>();
return entityRepo.Find("somedomain/api/orders?mode=0", _identity);
}