C# Post Request Problem Comparing To Python - python

i have problem making post request in c#, i'm trying to make post request using c#
var values = new Dictionary<string, string>{
{ "email", "hello" },
{ "password", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("myapilink", content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
then i get 403 forbidden error code with message [ access denied], so when i try this request in python with the same api, same data, same every thing, using requests library
url = 'myapi.com'
data = F"email={email}&password={password}"
req = requests.post(url, data=data)
src = req.text
print(src)
i got another source, [ invalid username or password ] and that is the right source [ that should appear to me ] not like c#, so idont know is that c# problem or problem in httpclient in c#, what can i do with this ?

Related

Python requests post reponse 400

I have no idea where is error. My response is 400 cuz of it:
"errors":{"data":["The data field is required."
but i am sending 'data':
data = "{'example': 'example'}"
url = f'http://localhost:5219/myApi'
payload = {'data': str(data).encode('utf-8')}
req = requests.post(url, data=payload)
print(req.content)
response
b'{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-355ed090aff5fa10460587fe222edbbe-3b3927cf18b26b78-00","errors":{"data":["The data field is required."]}}'
how can i repair that?
i tried changing formats and other things but it didn't work pls help me
this is c# code from api:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Text.Json.Nodes;
namespace spyware.Api.Controllers
{
[Route("[controller]")]
[ApiController]
public class api : ControllerBase
{
[HttpPost]
public void GetResponse(string data)
{
Console.WriteLine(JsonConvert.DeserializeObject(data.ToString()));
}
}
}

login into Spotify through python requests module

I've been trying to connect my Spotify account using the requests module and I came across a problem
later on I tried to manipulate it on my Python code
import requests
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
response = requests.post(URL , json=payload)
print(response.status_code)
OUTPUT : 415
what went wrong ?
I don't think this is how you should interact with Spotify from code.
It has an API and you should use tokens for authentication or anything else from password.
Anyway you can try setting the correct media type when making the request:
URL = 'https://accounts.spotify.com/login/password'
payload = {
"username": "example#gmail.com",
"password": "123456",
"remember" : True
}
headers = { 'Content-Type':'application/x-www-form-urlencoded' }
response = requests.post(URL , json=payload, headers=headers)
you cannot use this url to send post request as it has "recaptchaToken" which you need pass in your payload which is getting generated dynamically. Hence it is not a good idea to use this approach.
Instead you can use API to achieve the same.
https://github.com/plamere/spotipy

APNS Notifications: Python HTTP/2 POST request returning 404 ({"reason":"BadPath"})

I am developing a watchOS app and I want to send push notifications to my users. I have enabled "Push Notifications" in signing and capabilities and a file called "app_name WatchKit Extension" was generated containing one entitlement called APS environment whose value is set to "development".
I have also generated a .p8 file in the Apple Developer Website with the authentication key and that also gives me the key id.
I have created a Swift class called App Delegate that conforms to UNUserNotificationCenterDelegate. I have implemented the method applicationDidFinishLaunching from where I call WKExtension.shared().registerForRemoteNotifications(). Then I implemented the didRegisterForRemoteNotifications where I receive the device token and convert it into a string by executing these lines of code:
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
Then I send the token to the server. In the server I have a Python script that makes the post request to https://api.sandbox.push.apple.com:443 with the headers and notification payload. However, I always get a 404 error ({"reason":"BadPath"}).
I don't know what I am doing wrong. Am I configuring anything wrong? This is the Python script I am using:
import time
import httpx
import asyncio
import jwt
ALGORITHM = 'ES256'
APNS_AUTH_KEY = "path to .p8 file"
f = open(APNS_AUTH_KEY)
secret = f.read()
apns_token = jwt.encode(
{
'iss': 'cert_id',
'iat': time.time()
},
secret,
algorithm=ALGORITHM,
headers={
'alg':ALGORITHM,
'kid':'key_id'
}
)
dev_server = "https://api.sandbox.push.apple.com:443"
device_token = "9fe2814b6586bbb683b1a3efabdbe1ddd7c6918f51a3b83e90fce038dc058550"
headers = {
'method': 'POST',
'path': '/3/device/{0}'.format(device_token),
'autorization': 'bearer {0}'.format(apns_token),
'apns-push-type': 'myCategory',
'apns-expiration': '0',
'apns-priority': '10',
}
payload = {
"aps" : {
"alert" : {
"title" : "Hello Push",
"message": "This is a notification!"
},
"category": "myCategory"
}
}
async def test():
async with httpx.AsyncClient(http2=True) as client:
client = httpx.AsyncClient(http2=True)
r = await client.post(dev_server, headers=headers, data=payload)
print(r.text)
print(r)
asyncio.run(test())
Is there anything wrong with the way I am setting things up or performing the post request?
Thank you for your help!

How to send json POST request using requests if the website uses jwt?

i am trying to send POST request to login to this URL
, i first checked the network tab and found out the the post request is being sent to this
url : https://api-my.te.eg/api/user/login?channelId=WEB_APP
and the request payload is:
{
"header":{
"timstamp":0,
"customerId":null,
"msisdn":null,
"messageCode":null,
"responseCode":"1200",
"responseMessage":"Your Session has been expired, please sign in to continue",
"locale":null,
"referenceId":null,
"channelId":null,
"responeAdditionalParameters":null
},
"body":null
}
Here is the code :
import requests
import calendar
import time
#Here i tried to send a generated timestamp, idk if this is needed or not
ts = calendar.timegm(time.gmtime())
loginUrl = 'https://api-my.te.eg/api/user/login?channelId=WEB_APP'
values = {
"msisdn": MobileNumberID,
"timestamp": str(ts),
"locale": "Ar"
}
data = {
"password": PasswordID
}
url = requests.post(loginUrl , data=data , headers=values)
print(url.text)
I looked at the site and in the body they are also passing a header property in the data
So you should use
data = {
"header": {
"msisdn": "024568478",
"timestamp": "1592337873",
"locale": "Ar"
},
"body": {
"password": "PJGkRJte5ntnKt9TQ8XM3Q=="
}
}
and in headers you should pass the native headers probably something like:
headers={'Content-Type': 'application/json', }
but i also see by when you log into this site they pass a jwt argument in the headers. Looks like its some sort of built in security. So it looks like you can not use this API. Its only for the backend of this site.
Did you search the site to see if they have API documentation, maybe their is written how you can calculate the value for jwt?
EDIT:
When you get the login working this is. How to use sessions in python requests:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
If you do not get arround the jwt. You can uses Selenium in python. It works by automating a webbrowser. So you can open chrome tell it wich page to load, fill in your login form and read the html of elements in the browser. This will work on 95% of the websites. Some even have protections against it. Some sites use cloudflare, they are protected from selenium automation.

How to use header key from the api to authenticate URL in iOS Swift?

I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without any key implementation:
Alamofire.request(.GET,"http://name/user_data/\(userName)#someURL.com").responseJSON { response in // 1
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}
I have a key as "appkey" and value as a "test" in my api. If anyone can help. Thank you!
This should work
let headers = [
"appkey": "test"
]
Alamofire.request(.GET, "http://name/user_data/\(userName)#someURL.com", parameters: nil, encoding: .URL, headers: headers).responseJSON {
response in
//handle response
}
let headers: HTTPHeaders = [
"Accept": "application/json",
"appkey": "test"
]
Alamofire.request("http://name/user_data/\(userName)#someURL.com", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}

Categories

Resources