using (var client = new System.Net.Http.HttpClient())
{
var response = client.GetAsync(fullUrl).Result;
}
I am creating HTTP client as above to consume a RESTfull service.
I should be able to set proxy for this service request.
How can I set proxy server specific to this service request only?
System.Net.Http.HttpClient don't have TransportSettings propert and about Microsoft.Http assembly is unknown.
uSING Microsoft.Http I can
HttpClient client = new HttpClient();
/*Set Credentials to authenticate proxy*/
client.TransportSettings.Proxy = new WebProxy(proxyAddress);
client.TransportSettings.Proxy.Credentials = CredentialCache.DefaultCredentials;
client.TransportSettings.Credentials = CredentialCache.DefaultCredentials;
client.BaseAddress = new Uri(this.baseUrl);
var response = client.Get(fullUrl);
var jsonResponce = response.Content.ReadAsJsonDataContract<mYResponseoBJECT>();
public static T ReadAsJsonDataContract<T>(this HttpContent content)
{
return (T)content.ReadAsJsonDataContract<T>(new DataContractJsonSerializer(typeof(T)));
}
Related
I am beginner. Take it easy on me.
I want to set or connect proxy on that piece of code
var requestMsg = new HttpRequestMessage(GetHttpMethod(method), url);
if (method != APIMethod.GET)
{
var serializedContent = JsonConvert.SerializeObject(request);
requestMsg.Content = new StringContent(serializedContent, Encoding.UTF8, "application/json");
}
WebProxy myproxy = new WebProxy("xxx.xx.xx.xx", 8080);
requestMsg.Proxy = myproxy; <------ error
HttpResponseMessage task = await httpClientFactory.CreateClient().SendAsync(requestMsg);
please help me set proxy hard code
i read these but i cant understand
Proxy with HTTP Requests
C# Connecting Through Proxy
You can try to use HttpClient.DefaultProxy to set the global Http proxy.
HttpClient.DefaultProxy = new WebProxy("xxx.xx.xx.xx", 8080);
I need to add http headers to the HttpClient before I send a request to a web service. How do I do that for an individual request (as opposed to on the HttpClient to all future requests)? I'm not sure if this is even possible.
var client = new HttpClient();
var task =
client.GetAsync("http://www.someURI.com")
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.
var client = new HttpClient();
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
.ContinueWith((taskwithmsg) =>
{
var response = taskwithmsg.Result;
var jsonTask = response.Content.ReadAsAsync<JsonObject>();
jsonTask.Wait();
var jsonObject = jsonTask.Result;
});
task.Wait();
When it can be the same header for all requests or you dispose the client after each request you can use the DefaultRequestHeaders.Add option:
client.DefaultRequestHeaders.Add("apikey","xxxxxxxxx");
To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server.
eg:
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(someURL)
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
client.execute(request);
Default header is SET ON HTTPCLIENT to send on every request to the server.
From my web service (A) usng impersonation i would like call a WebAPI service (B) using HttpClient. But the service B always gets the system user of service A even though i do impersonation there.
var baseUri = "http://service/api/"
var handler = new HttpClientHandler { UseDefaultCredentials = true };
var client = new HttpClient(handler) { BaseAddress = baseUri };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("ContentType", new List<string> { "application/json"});
var dataDto = new DataDto();
var json = JsonConvert.SerializeObject(dataDto );
var content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(SubUrl, content);
I know that Kerberos and SPN are set up correctly because it works using WebClient.
I think the problem is, that HttpClient.PostAsync creates a new task and therefore a new thread running under the credentials of the appPool of service A.
Does anyone know how i could force the task to run under the imperonated credentials?
I do not have access to the aspnet_config.config so the solution proveded here does not work for me.
Thanks a lot!
Tschuege
I have to call a restful API, but the only details I have are an API ID and an API key.
I am trying to use Restsharp library code like this.
var client = new RestClient("https://xxxxxxx");
client.Authenticator = new HttpBasicAuthenticator("xxxxx", "yyyyyy");
I get a 401 authorization required error.
Could you please point me in the right direction.
Thanks.
Here is the solution that i came up with.
this returns the client object
private RestClient InitializeAndGetClient()
{
var cookieJar = new CookieContainer();
var client = new RestClient("https://xxxxxxx")
{
Authenticator = new HttpBasicAuthenticator("xxIDxx", "xxKeyxx"),
CookieContainer = cookieJar
};
return client;
}
and you can use the method like
var client = InitializeAndGetClient();
var request = new RestRequest("report/transaction", Method.GET);
request.AddParameter("option", "value");
//Run once to get cookie.
var response = client.Execute(request);
//Run second time to get actual data
response = client.Execute(request);
Hope this helps you.
Prakash.
I know this is old but this is partial to what I needed:
var cookieJar = new CookieContainer();
var client = new RestClient("https://xxxxxxx")
{
Authenticator = new HttpBasicAuthenticator("[username]", "[password]"),
CookieContainer = cookieJar
};
Then right after I made the request object I had to add the API_KEY header:
var request = new RestRequest("[api]/[method]"); // this will be unique to what you are connecting to
request.AddHeader("API_KEY", "[THIS IS THE API KEY]");
I am calling a RESTful web service (hosted in Azure) from my Windows Store App (Windows Metro App). This is the Service definition:
[OperationContract]
[WebInvoke(UriTemplate="/Test/PostData",
RequestFormat= WebMessageFormat.Json,
ResponseFormat= WebMessageFormat.Json, Method="POST",
BodyStyle=WebMessageBodyStyle.WrappedRequest)]
string PostDummyData(string dummy_id, string dummy_content, int dummy_int);
From the Windows Store Apps, when calling, I am getting Request Error after posting (it did not even hit the breakpoint I placed in PostDummyData. I have tried the following methods:
Using a StringContent object
using (var client = new HttpClient())
{
JsonObject postItem = new JsonObject();
postItem.Add("dummy_id", JsonValue.CreateStringValue("Dummy ID 123"));
postItem.Add("dummy_content", JsonValue.CreateStringValue("~~~Some dummy content~~~"));
postItem.Add("dummy_int", JsonValue.CreateNumberValue(1444));
StringContent content = new StringContent(postItem.Stringify());
using (var resp = await client.PostAsync(ConnectUrl.Text, content))
{
// ...
}
}
Using a HttpRequestMessage
using (var client = new HttpClient())
{
JsonObject postItem = new JsonObject();
postItem.Add("dummy_id", JsonValue.CreateStringValue("Dummy ID 123"));
postItem.Add("dummy_content", JsonValue.CreateStringValue("~~~Some dummy content~~~"));
postItem.Add("dummy_int", JsonValue.CreateNumberValue(1444));
StringContent content = new StringContent(postItem.Stringify());
HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, ConnectUrl.Text);
msg.Content = content;
msg.Headers.TransferEncodingChunked = true;
using (var resp = await client.SendAsync(msg))
{
// ...
}
}
I'd figured that it may be the content-type header that is having problem (last checked it was set to plain text, but I can't find a way to change it).
The HTTP GET methods are all working fine though. Would appreciate if somebody can point me to a correct direction. Thanks!
You should set the content-type in the StringContent object:
StringContent content = new StringContent(postItem.Stringify());
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/json");
or directly in the constructor:
StringContent content = new StringContent(postItem.Stringify(),
Encoding.UTF8, "text/json");