LoL Live API Usage - c#

I've been trying to figure out how to use the League of Legends live API. I've had success using the endpoints like this: /lol/summoner/v4/summoners/by-name/{summonerName}
but when it comes to using endpoints like this (for live game data): GET https://127.0.0.1:2999/liveclientdata/allgamedata
I get the error
"Cannot connect to destination host"
Here is sample code I've been trying:
private IEnumerator Test()
{
string url = "https://127.0.0.1:2999/liveclientdata/activeplayername";
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
yield return webRequest.SendWebRequest();
string error = webRequest.error;
if (error != null)
{
Debug.LogError("[LoLAPI] - " + error);
}
else
{
Debug.Log(webRequest.downloadHandler.text);
}
}
}
Am I missing something?
Thanks

The implementation of UnityWebRequest will not accept self-signed SSL certificates by default. Try adding this:
public class UncheckedCertificateHandler: CertificateHandler
{
protected override bool ValidateCertificate(byte[] certData)
{
// certificate validation always returns true
return true;
}
}
Then when you create the web request:
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
www.certificateHandler = new UncheckedCertificateHandler();
yield return webRequest.SendWebRequest();
Or alternatively, just use http:// if it is available.

Related

How can I login with OAuth2.0 in DevOps API in C#?

I tried many API Calls with Postman and It works fine but I only get it to work with PAT.
Below you can find my API Call with my PAT. How can I change it to OAuth2.0?
By the way, I'm using the DataVerse API with OAuth2.0 but rewrite doesnt work.
EDIT:
I used the OAuthWebSample but there is another Error:
When I click on "Authorize" it says "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
What I need to do to get it to work is to copy the website-url given in the publish section in visual studio and switch it.
So I got PUBLISHEDNAME.azurewebsites.net instead of APPNAME.azurewebsites.net
When I'm switching the CallbackUrl in web.config to PUBLISHEDNAME.azurewebsites.net I'll get a 400.
How can I fix it?
private const string URL = "DEV LINK";
string testToken = "PAT";
public TextMesh APIText;
public TextMeshProUGUI Text;
// Start is called before the first frame update
void Start()
{
}
public void GenerateDevOps()
{
StartCoroutine(ProcessDevOps(URL));
}
public IEnumerator ProcessDevOps(string uri)
{
using (UnityWebRequest request = UnityWebRequest.Get(uri))
{
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Basic" + " " + testToken);
yield return request.SendWebRequest();
if (request.isNetworkError)
{
Debug.Log(request.error);
}
else
{
Debug.Log(request.downloadHandler.text);
Text.text = request.downloadHandler.text;
/* var data = JsonConvert.DeserializeObject<Root>(request.downloadHandler.text);
var dataInhalt = data.value.ToArray();
Debug.Log(dataInhalt);
foreach (Value content in dataInhalt)
{
string name = content.firstname;
string lastname = content.lastname;
//textapi.text = name + " " + lastname;
names = names + name + lastname + Environment.NewLine;
}
APIHeader.text = URL;
m_Object.text = names;
*/
}
}
}
The 404 error code means that the resource doesn't exist, or the authenticated user doesn't have permission to see that it exists. So here are two troubleshooting advices:
Check your REST API using PAT to see whether the error is about the API.
Configure OAuth 2.0 exactly as this document. In particular, make sure you have configured permissions correctly, which means that you can use the access token to read data and send it back.

Cannot POST data using UnityWebRequest in Unity, it gives Error: HTTP/1.1 500 Internal Server Error

I cannot POST data in Json Format using UnityWebRequest in Unity. It gives error
Error: HTTP/1.1 500 Internal Server Error
I am using Webservice made in ASP.NET Core and hosted locally on IIS Express.
Here is my C# Code in Unity
public class AddUsers : MonoBehaviour
{
IEnumerator addOrUpdateUser()
{
User user = new User()
{
Id = "0001",
Name = "John",
}
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", JsonConvert.SerializeObject(user));
req.SetRequestHeader("Content-Type", "application/json");
req.certificateHandler = new BypassCertificate();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError || req.isError)
print("Error: " + req.error);
print(req.downloadHandler.text);
}
}
[Serializable]
public class UserDetails
{
public string Id { get; set; }
public string Name { get; set; }
}
Here is my ASP.NET Core Code using Entity Framework Core
[HttpPost]
string AddNewUser([FromBody]User user)
{
Context.LogoQuizUsers.Add(user); // I am getting System.NullReferenceException here
Context.SaveChanges();
return "Inserted Id: " + user.Id;
}
Post data as raw - body just as you would send using Postman or any similar interface.
Set Request's UploadHandler as UploadHandlerRaw. Add and Change your statement
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", "POST");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user))) as UploadHandler;
Hence the final code will be
IEnumerator addOrUpdateUser()
{
//...
UnityWebRequest req = UnityWebRequest.Post("http://localhost:58755/User/AddNewUser", "POST");
req.SetRequestHeader("Content-Type", "application/json");
req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(user))) as UploadHandler;
req.certificateHandler = new BypassCertificate();
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError || req.isError)
print("Error: " + req.error);
print(req.downloadHandler.text);
//...
}
Rest of the code is correct.
Look at this topic
Inside the Unity editor:
Go to Window -> Package Manager.
In the topbar of the new window, search the "Packages : XXXXXX" drop-down and select "Unity Registry".
Search the "WebGl publisher" and install / import it.
IIIFFF the package doesn't appear:
In the same Package manager windows, click the "+" button -> Add from git.
Add the following:
com.unity.connect.share
This will automatically add the WebGL Publisher.
It helped me to resolve the problem

Using C# to authenticate an SSL certificate

I'm trying to communicate with a backend server using SSL.
I'm trying using HttpClient from the System.Net.Http library, but I couldn't get it working.
This is my code (Debug.Log is just a print since I'm using Unity):
public static async Task DownloadPageAsync(string web)
{
try
{
HttpClient cl = new HttpClient();
string body = await cl.GetStringAsync(new Uri(web));
Debug.Log(web);
}
catch (HttpRequestException e)
{
Debug.Log(e.InnerException.Message);
}
catch (Exception ex)
{
Debug.Log(ex.ToString());
}
}
When I try it in a web with a bad certificate, it gives: "Error: TrustFailure (The authentication or decryption has failed.)", which is fine. The problem is that good certificates also triggers an error: "Error: SecureChannelFailure (The authentication or decryption has failed.)".
I've saw other answers saying that simply accepting all the certificates works fine, but I need to check if it's a valid certificate or not.
¿Is there a way of doing it with HttpClient? ¿Or with some other class?
Btw, I'm only using it to send POST request, and receiving a simple string.
Thank you!
For UnityWebRequest since Unity 2018.1 there is the UnityWebRequest.certificateHandler e.g.
IEnumerator GetRequest(string uri)
{
UnityWebRequest request = UnityWebRequest.Get(uri);
request.certificateHandler = new AcceptAllCertificatesSignedWithASpecificPublicKey();
yield return request.SendWebRequest ();
if (request.isNetworkError)
{
Debug.Log("Something went wrong, and returned error: " + request.error);
}
else
{
// Show results as text
Debug.Log(request.downloadHandler.text);
}
}
And the implementation of the example CertificateHandler:
using UnityEngine.Networking;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
// Based on https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#.Net
class AcceptAllCertificatesSignedWithASpecificPublicKey: CertificateHandler
{
// Encoded RSAPublicKey
private static string PUB_KEY = "mypublickey";
protected override bool ValidateCertificate(byte[] certificateData)
{
X509Certificate2 certificate = new X509Certificate2(certificateData);
string pk = certificate.GetPublicKeyString();
if (pk.ToLower().Equals(PUB_KEY.ToLower()))
{
return true;
}
return false;
}
}
(Source)
For HttpClient see Make Https call using HttpClient

Lambda Function using c# cannot invoke external HTTPS APIs

I am trying to invoke External APIs from AWS lambda function written in c#. The Lamda function is deployed in No VPC mode. I am calling this function from Alexa skill. The code works fine for an http request, but its not working for https.
The below code works when I use http://www.google.com.
But, if I replace http with https, then I get the error in the cloud watch saying:
"Process exited before completing request."
Even the log written in catch is not getting logged in cloud watch.
public class Function
{
public const string INVOCATION_NAME = "bingo";
public async Task<SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context)
{
var requestType = input.GetRequestType();
if (requestType == typeof(IntentRequest))
{
string response = "";
IntentRequest request = input.Request as IntentRequest;
response += $"About {request.Intent.Slots["carmodel"].Value}";
try
{
using (var httpClient = new HttpClient())
{
Console.WriteLine("Trying to access internet");
//var resp=httpClient.GetAsync("http://www.google.com").Result // this works perfect!
var resp = httpClient.GetAsync("https://www.google.com").Result; // this throws error
Console.WriteLine("Call was successful");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception from main function " + ex.Message);
Console.WriteLine(ex.InnerException.Message);
Console.WriteLine(ex.StackTrace);
}
return MakeSkillResponse(response, true);
}
else
{
return MakeSkillResponse(
$"I don't know how to handle this intent. Please say something like Alexa, ask {INVOCATION_NAME} about Tesla.",
true);
}
}
private SkillResponse MakeSkillResponse(string outputSpeech, bool shouldEndSession,
string repromptText = "Just say, tell me about car models to learn more. To exit, say, exit.")
{
var response = new ResponseBody
{
ShouldEndSession = shouldEndSession,
OutputSpeech = new PlainTextOutputSpeech { Text = outputSpeech }
};
if (repromptText != null)
{
response.Reprompt = new Reprompt() { OutputSpeech = new PlainTextOutputSpeech() { Text = repromptText } };
}
var skillResponse = new SkillResponse
{
Response = response,
Version = "1.0"
};
return skillResponse;
}
}
The issue was resolved by updating the library version.
System.Net.Http v4.3.4 was not completely compatible with dotnet core v1.
So outbound http calls were working but not https calls. Changing the version of System.net.http resolved the issue.

Unity: Post Request unable to connect to destination host

I'm familiar with Unity but new to trying to communicate with servers. I'm trying to set up a login screen but I'm having troubling Posting to the server properly. The strange part is the Get is working fine, but the Post turns up the following Error :
Cannot connect to destination host Network
UnityEngine.Debug:Log(Object)
LoginHandler:CheckForNetworkErrors(UnityWebRequest) (at
Assets/Scripts/LoginHandler.cs:120)
<LoginUser>c__Iterator2:MoveNext() (at Assets/Scripts/LoginHandler.cs:92)
.UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
I'm using a test URL to make sure it was't an issue with the original. Both return the same error. The following code is sent once the player hits a login button. Any ideas on what im doing wrong here?
public IEnumerator LoginUser()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest get = UnityWebRequest.Get(testURL))
{
yield return get.Send();
ParseCSRF(get.downloadHandler.text);
CheckForNetworkErrors(get);
}
WWWForm form = new WWWForm();
form.AddField("username", username.text);
form.AddField("password", password.text);
form.AddField("_csrf", csrf);
using (UnityWebRequest post = UnityWebRequest.Post(WWW.EscapeURL(testURL), form))
{
yield return post.SendWebRequest();
CheckForNetworkErrors(post);
}
}
public void CheckForNetworkErrors(UnityWebRequest www)
{
if(www.isNetworkError)
{
Debug.Log(www.error + " Network");
}
else if (www.isHttpError)
{
Debug.Log(www.error + " http");
}
else
{
Debug.Log("Form upload complete!" + www.downloadHandler.text);
}
}
I have tested with the code I wrote below:
void Start()
{
StartCoroutine(GetCrt());
}
IEnumerator GetCrt()
{
string testURL = "https://www.google.com/";
using (UnityWebRequest www = UnityWebRequest.Get(testURL))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Get Request Completed!");
}
}
}
It's working fine.
For the post request you need a real form data, you can't send a post request to google.com.
Hope this help you.
Happy Coding!

Categories

Resources