本文整理汇总了C#中JsonServiceClient类的典型用法代码示例。如果您正苦于以下问题:C# JsonServiceClient类的具体用法?C# JsonServiceClient怎么用?C# JsonServiceClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonServiceClient类属于命名空间,在下文中一共展示了JsonServiceClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateClient
private static JsonServiceClient CreateClient(string baseUrl, string token)
{
var client = new JsonServiceClient(baseUrl.TrimEnd('/'));
client.AddHeader(HttpHeaders.Authorization, @"Bearer {0}".Fmt(token));
return client;
}
示例2: Can_report_progress_when_downloading_async
public async Task Can_report_progress_when_downloading_async()
{
var hold = AsyncServiceClient.BufferSize;
AsyncServiceClient.BufferSize = 100;
try
{
var asyncClient = new JsonServiceClient(ListeningOn);
var progress = new List<string>();
//Note: total = -1 when 'Transfer-Encoding: chunked'
//Available in ASP.NET or in HttpListener when downloading responses with known lengths:
//E.g: Strings, Files, etc.
asyncClient.OnDownloadProgress = (done, total) =>
progress.Add("{0}/{1} bytes downloaded".Fmt(done, total));
var response = await asyncClient.GetAsync(new TestProgress());
progress.Each(x => x.Print());
Assert.That(response.Length, Is.GreaterThan(0));
Assert.That(progress.Count, Is.GreaterThan(0));
Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded"));
Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded"));
}
finally
{
AsyncServiceClient.BufferSize = hold;
}
}
示例3: getBuild
/// <summary>
/// Get a new build
/// </summary>
/// <returns>BuildInfo object or null on error/no build</returns>
public static BuildInfo getBuild()
{
Console.WriteLine("* Checking for builds...");
var client = new JsonServiceClient (apiurl);
try
{
var buildInfo = client.Post (new CheckForBuild
{
token = Uri.EscapeDataString (Config.token)
});
if (buildInfo != null)
{
return buildInfo;
}
}
catch (WebServiceException ex)
{
if(ex.StatusCode == 404)
{
Console.WriteLine ("* Nothing");
}
else
{
Console.WriteLine ("* Failed");
}
}
return null;
}
示例4: Populator
public Populator(string url, double latitude, double longitude)
{
Url = url;
Latitude = latitude;
Longitude = longitude;
_client = new JsonServiceClient(Url);
}
示例5: DispatchTrip
public override Gateway.DispatchTripResponse DispatchTrip(Gateway.DispatchTripRequest request)
{
Logger.BeginRequest("DispatchTrip sent to " + name, request);
GatewayService.Dispatch dispatch = new GatewayService.Dispatch
{
access_token = AccessToken,
PassengerId = request.passengerID,
PassengerName = request.passengerName,
Luggage = request.luggage,
Persons = request.persons,
PickupLat = request.pickupLocation.Lat,
PickupLng = request.pickupLocation.Lng,
PickupTime = request.pickupTime,
DropoffLat = request.dropoffLocation == null ? (double?) null : request.dropoffLocation.Lat,
DropoffLng = request.dropoffLocation == null ? (double?) null : request.dropoffLocation.Lng,
PaymentMethod = request.paymentMethod,
VehicleType = request.vehicleType,
MaxPrice = request.maxPrice,
MinRating = request.minRating,
PartnerId = request.partnerID,
FleetId = request.fleetID,
DriverId = request.driverID,
TripId = request.tripID
};
JsonServiceClient client = new JsonServiceClient(RootUrl);
GatewayService.DispatchResponse resp = client.Get<GatewayService.DispatchResponse>(dispatch);
Gateway.DispatchTripResponse response = new Gateway.DispatchTripResponse
{
result = resp.ResultCode,
};
Logger.EndRequest(response);
return response;
}
示例6: Does_AutoWire_ActionLevel_RequestFilters
public void Does_AutoWire_ActionLevel_RequestFilters()
{
try
{
var client = new JsonServiceClient(ListeningOn);
var response = client.Get(new ActionAttr());
var expected = new List<string> {
typeof(FunqDepProperty).Name,
typeof(FunqDepDisposableProperty).Name,
typeof(AltDepProperty).Name,
typeof(AltDepDisposableProperty).Name,
};
response.Results.PrintDump();
Assert.That(expected.EquivalentTo(response.Results));
}
catch (Exception ex)
{
ex.Message.Print();
throw;
}
}
示例7: GetAccessToken
// this performs our main OAuth authentication, performing
// the request token retrieval, authorization, and exchange
// for an access token
public IToken GetAccessToken()
{
var consumerContext = new OAuthConsumerContext () {
ConsumerKey = "anyone"
};
var rest_client = new JsonServiceClient (BaseUri);
var url = new Rainy.WebService.ApiRequest ().ToUrl("GET");
var api_ref = rest_client.Get<ApiResponse> (url);
var session = new OAuthSession (consumerContext, api_ref.OAuthRequestTokenUrl,
api_ref.OAuthAuthorizeUrl, api_ref.OAuthAccessTokenUrl);
IToken request_token = session.GetRequestToken ();
// we dont need a callback url
string link = session.GetUserAuthorizationUrlForToken (request_token, "http://example.com/");
// visit the link to perform the authorization (no interaction needed)
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create (link);
// disallow auto redirection, since we are interested in the location header only
req.AllowAutoRedirect = false;
// the oauth_verifier we need, is part of the querystring in the (redirection)
// 'Location:' header
string location = ((HttpWebResponse)req.GetResponse ()).Headers ["Location"];
var query = string.Join ("", location.Split ('?').Skip (1));
var oauth_data = System.Web.HttpUtility.ParseQueryString (query);
IToken access_token = session.ExchangeRequestTokenForAccessToken (request_token, oauth_data ["oauth_verifier"]);
return access_token;
}
示例8: Test12
void Test12(JsonServiceClient client)
{
Console.WriteLine("~~~~~ DeleteUser (newuser3) ~~~~~~~~~");
UserResponse response = client.Delete<XamarinEvolveSSLibrary.UserResponse>("User/newuser3");
Console.WriteLine("Expected null: " + response.Exception);
Console.WriteLine();
}
示例9: btnTest_Click
private async void btnTest_Click(object sender, RoutedEventArgs e)
{
//Make all access to UI components in UI Thread, i.e. before entering bg thread.
var name = txtName.Text;
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
var client = new JsonServiceClient("http://localhost:2000/")
{
//this tries to access UI component which is invalid in bg thread
ShareCookiesWithBrowser = false
};
var fileStream = new MemoryStream("content body".ToUtf8Bytes());
var response = client.PostFileWithRequest<UploadFileResponse>(
fileStream, "file.txt", new UploadFile { Name = name });
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
lblResults.Content = "File Size: {0} bytes".Fmt(response.FileSize);
});
}
catch (Exception ex)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
lblResults.Content = ex.ToString();
});
}
});
}
示例10: JsonClientShouldGetPlacesToVisit
public void JsonClientShouldGetPlacesToVisit()
{
var client = new JsonServiceClient(_listeningOn);
var testRequest = new AllPlacesToVisitRequest();
var response = client.Get(testRequest);
Assert.AreEqual("Capital city of Australia",response.Places.FirstOrDefault().Description);
}
示例11: Main
public static void Main(string[] args)
{
JsonServiceClient client = new JsonServiceClient("http://127.0.0.1:8888/");
client.Timeout = TimeSpan.FromSeconds(60);
client.ReadWriteTimeout = TimeSpan.FromSeconds(60);
client.DisableAutoCompression = true;
int success = 0, error = 0;
Parallel.For(0, 100, i => {
try
{
Console.WriteLine(i.ToString());
StatesResult result = client.Get(new GetLastStates());
if(result.List.Count < 4000)
error++;
Console.WriteLine("Received " + result.List.Count + " items");
success++;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
error++;
}
});
Console.WriteLine(string.Format("Test completed. Success count:{0}; Error count:{1}",success,error));
client.Dispose();
}
示例12: OnTestFixtureSetUp
public void OnTestFixtureSetUp()
{
Client = new JsonServiceClient(BaseUri);
var response = Client.Post<AuthenticateResponse>("/auth",
new Authenticate { UserName = "test1", Password = "test1" });
}
示例13: RunTests
public void RunTests()
{
byte[] imageData;
using (Image srcImage = Image.FromFile(@"D:\Bill\Code\XamarinEvolve2013Project\TestSSAPI\testavatar.jpg"))
{
using (MemoryStream m = new MemoryStream())
{
srcImage.Save(m, ImageFormat.Jpeg);
imageData = m.ToArray(); //buffers
}
}
JsonServiceClient client = new JsonServiceClient(SystemConstants.WebServiceBaseURL);
UserAvatar userAvatar = new UserAvatar()
{
UserName = "billholmes",
Data = imageData,
};
UserAvatarResponse response = client.Post<UserAvatarResponse>("UserAvatar", userAvatar);
//response = client.Delete<UserAvatarResponse>("UserAvatar/billholmes");
return;
}
示例14: Test_PostWithBadHostnameAndGetMessage_StatusIsFailed
public void Test_PostWithBadHostnameAndGetMessage_StatusIsFailed()
{
// Create message
var postRequest = new CreateMessage
{
ApplicationId = 1,
Bcc = new[] { "[email protected]" },
Body = "This is a test email.",
Cc = new[] { "[email protected]" },
Connection = new Connection
{
EnableSsl = false,
Host = "nonexistant",
Port = 25
},
Credential = new Credential(),
From = "[email protected]",
ReplyTo = new[] { "[email protected]" },
Sender = "[email protected]",
Subject = "Test Message",
To = new[] { "[email protected]" }
};
var client = new JsonServiceClient("http://localhost:59200/");
var postResponse = client.Post(postRequest);
// Get message
var getRequest = new GetMessage
{
Id = postResponse.Id
};
var getResponse = client.Get(getRequest);
Assert.Equal(3, getResponse.Status.TypeMessageStatusId);
Assert.Equal(postResponse.Id, getResponse.Id);
}
示例15: TryLogin
public void TryLogin()
{
using(var tempDb = new TempFile())
{
//GlobalProxySelection.Select = new WebProxy("127.0.0.1", 8888); // proxy via Fiddler2.
using (var server = new Server() { Port = 8000, SqliteFile = tempDb.Path })
{
server.Start();
// log in
var restClient = new JsonServiceClient(FakeServer.BaseUri);
var response = restClient.Post<AuthResponseEx>(
"/api/auth/credentials?format=json",
new Auth()
{
UserName = "tech",
Password = "radar",
RememberMe = true
});
response.SessionId.ShouldMatch(@"[a-zA-Z0-9=+/]{20,100}");
response.UserName.ShouldBe("tech");
response.UserId.ShouldMatch(@"^[a-zA-Z0-9_-]{8}$");
// log out
var logoutResponse = restClient.Delete<AuthResponse>("/api/auth/credentials?format=json&UserName=tech");
logoutResponse.SessionId.ShouldBe(null);
// can't come up with a good way to verify that we logged out.
}
}
}