C# HttpWebRequest Exeption Cookies - python

Hi I'm trying to convert a python code to C#. My Problem is, that I have a problem to make a HttpWebRequest. I don't get the cookies for the POST Request.
The Website response is 404. That is correct. But I think, I need the cookies for the POST request.
Is it correctly transleted? I have not done a HttpWebRequest yet.
C# Code:
public string email = "test#example.com"
public string password = "123456"
public string client_id = "111111111111"
public string login_url = "https://account.komoot.com/v1/signin"
var headers = new Dictionary<string, string> {
{"Content-Type", "application/json"}};
var payload = new Dictionary<string, string> {
{"email", email},
{"password", password},
{"reason", "null"}};
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = new CookieContainer();
var response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
var exeptionResponse = ex.Response;
var cookies = exeptionResponse ["Cookies"];
throw new WebException();
}
try
{
var request = (HttpWebRequest)WebRequest.Create(login_url);
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "application/json";
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.Write(payload);
}
using (var responseStream = request.GetResponse().GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
var result = reader.ReadToEnd();
Console.WriteLine(result);
}
}
catch (Exception exe)
{
throw new Exception();
}
Python Code:
import requests
import json
email = "test#example.com"
password = "123456"
client_id = "111111111111"
login_url = "https://account.komoot.com/v1/signin"
tour_url = f"https://www.komoot.de/user/{client_id}/tours"
s = requests.Session()
res = requests.get(login_url)
cookies = res.cookies.get_dict()
headers = {
"Content-Type": "application/json"
}
payload = json.dumps({
"email": email,
"password": password,
"reason": "null"
})
s.post(login_url,
headers=headers,
data=payload,
cookies=cookies,
)
url = "https://account.komoot.com/actions/transfer?type=signin"
s.get(url)
headers = {"onlyprops": "true"}
response = s.get(tour_url, headers=headers)
if response.status_code != 200:
print("Something went wrong...")
exit(1)
data = response.json()
tours = data["user"]["_embedded"]["tours"]["_embedded"]["items"]
for idx in range(len(tours)):
print(f"({idx+1}) {tours[idx]['name']}")
tour_nr = int(input("Tour ID: "))
tour_nr -= 1
tour_url = tours[tour_nr]["_links"]["coordinates"]["href"]
response = s.get(tour_url, headers=headers)
tour_data = json.loads(response.text)
tour = tours[tour_nr]
tour['coordinates'] = tour_data
print("Title:", T.name())
print(f"Duration: {T.duration()}s")
Tanks for your help!

Try it
public async Task<string> HttpClientAsync(string json, string token)
{
try
{
var JsonData = new StringContent(json, Encoding.UTF8, "application/json");
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
using (var client = new HttpClient(handler))
{
// System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var result = await client.PostAsync(url, JsonData);
string resultContent = await result.Content.ReadAsStringAsync();
return resultContent;
}
}
catch (Exception e)
{
return e.Message;
}
}

Related

Share Plex library in Dart

Hi I’m figuring out how to share Plex library in dart.
I'm helping myself with this working script in python ( it works)
https://gist.github.com/JonnyWong16/f8139216e2748cb367558070c1448636
unfortunately my code returns an http error 400, bad request
note: When I run the dart code there are no shared library.
maybe the payload is not correct :|
Thank for any help
import 'package:http/http.dart' as http;
class Server {
String token, ip, port;
Server(this.ip, this.port, this.token);
share() async {
var server_id = '00000000000000000000000000000000'; fake id
var library_section_ids = '97430074'; // right id , it works in python
var invited_id = '50819899'; // right id , it works in python
var headers = {
'Accept': 'application/json',
'X-Plex-Token': token,
};
var data =
'["server_id": $server_id,'
' "shared_server":["library_section_ids":[$library_section_ids],'
' "invited_id":$invited_id]';
var res = await http.post(
Uri.parse(
'https://plex.tv/api/servers/$server_id/shared_servers/'),
headers: headers,
body: data);
if (res.statusCode != 200) {
throw Exception('http.post error: statusCode= ${res.statusCode}');
}
print(res.body);
}
}
void main(List<String> arguments) async {
var srv = Server('xxx.yyy.xxx.yyy', '32400', '000000000-1111');
await srv.share();
}
The old code has a few bug and don't encode perfectly the data
I solved with 'dio' package and this link helped me a lot https://reqbin.com/
If the user has no shared library this code add a new one
import 'package:dio/dio.dart';
class Server {
String token;
Server(this.token);
test() async {
var serverId = '';
var librarySectionIds = ;
var invitedId = ;
var dio = Dio();
var data = {
"server_id": serverId,
"shared_server": {
"library_section_ids": librarySectionIds,
"invited_id": invitedId
}
};
dio.options.headers['Accept'] = 'application/json';
dio.options.headers["authorization"] = "Bearer $token";
var response = await dio.post(
'https://plex.tv/api/servers/$serverId/shared_servers/',
data: data);
print(response);
}

Python to GAS translation not working: get bad request error

I want the following code to be translated into GAS from python. I wrote the GAS version pasted below but it is not working. It must be something simple but I don't know the reason why I get this error. Any advice will be appreciated. Thanks.
import requests
requestId = "*******************"
url = "http://myapi/internal/ocr/"+requestid+"/ng"
payload={}
headers = {
'X-Authorization': 'abcdefghijklmn'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I wrote this at the moment but I get bad request error.
function sending(yesorno, requestId) {
var requestId = "*******************"
 var STAGING_KEY = "abcdefghijklmn"
var url = url = "http://myapi/internal/ocr/"+requestId+"/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': JSON.stringify(data),
'headers': {
'X-Authorization': STAGING_KEY
}
};
//Error processing
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options));
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Modified Code
function sending() {
var requestId = "*************************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/"+requestId+"/ng";
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
Logger.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error1')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error2: '+ e.toString())
}
}
Error
error2: Exception: Bad request:
I understood your situation as follows.
Your python script works fine.
You want to convert the python script to Google Apps Script.
When your Google Apps Script is run, an error Exception: Bad request: occurs.
In this case, how about the following modification? When response = requests.request("POST", url, headers=headers, data=payload) is used with payload={}, I think that at Google Apps Script, it's 'payload': {}.
Modified script:
function sending() {
var requestId = "*******************"
var STAGING_KEY = "abcdefghijklmn"
var url = "http://myapi/internal/ocr/" + requestId + "/ng"
var data = {}
var options = {
'muteHttpExceptions': true,
'method': 'post',
'payload': data,
'headers': {
'X-Authorization': STAGING_KEY
}
};
try {
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
console.log(response)
if (response && response["id"]) {
return 'sent';
} else {
//reportError("Invalid response: " + JSON.stringify(response));
//return 'error';
Logger.log('error')
}
} catch (e) {
//reportError(e.toString());
//return 'error';
Logger.log('error')
}
}
Note:
By the above modification, the request of Google Apps Script is the same as that of the python script. But if an error occurs, please check the URL and your STAGING_KEY, again. And, please check whether the API you want to use can access from the Google side.
Reference:
fetch(url, params)

FastApi cannot write cookie in reponse, in docker on vps, how to fix?

Cannot to sign in, i run localy in docker my container, i can sign-in on my machine and docker no error, but on my remote server i cannot to login, it doesn't write cookie in reponse, have no error, just don't write response. It just redirect me on my page which i setted,and after that i got error, cause i have no my cookie authorization key inside cookie.
video
My SignIn method
#auth_router.post('/signin')
async def sign_in(response: Response, username: str = Form(...), password: str = Form(...), recaptchav3: str = Form(...)) -> dict:
is_human = await verify_recaptcha(recaptchav3)
if is_human['success']:
user = await authenticate_user(username, password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid username or password',
)
user_obj = await User_Pydantic.from_tortoise_orm(user)
user_token = await generate_token(user_obj)
response.set_cookie(key="Authorization", value=user_token, httponly=True, secure=True, expires=(8*60*60))
response.headers["Authorization"] = user_token
user.jwt_token = user_token
await user.save()
return {
'access_token': user_token,
'token_type': 'bearer'
}
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid captcha',
)
How i submit my form js
const request = (method, url, data = null, redirectPage) => {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, true)
// xhr.setRequestHeader('Content-Type', 'multipart/form-data')
xhr.onerror = function (event) {
alert(event)
console.log(event);
};
xhr.onload = () => {
if (xhr.status === 200) {
return window.location.href = redirectPage;
return resolve(JSON.parse(xhr.responseText || '{}'))
} else {
alert(`Request failed with status ${xhr.status}`)
reject(new Error(`Request failed with status ${xhr.status}`))
return window.location.reload();
}
}
if (data) {
if (typeof data === 'string' || data instanceof String || typeof data.constructor == Object){
xhr.send(JSON.stringify(data))
} else {
xhr.send(data)
}
} else {
xhr.send()
}
})
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData, 'dashboard');
} else{
alert('Перезагрузите страницу');
}
}
})
I cannot understand why using the built-in method in fastapi it does not write on the remote server, it worked on the local one, but I solved the problem by writing. token via js.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie(cookieValue) {
var user = getCookie("Authorization");
if (user == "") {
if (cookieValue != "" && cookieValue != null) {
setCookie("Authorization", cookieValue, 365);
}
}
}
signInForm = getElementById('signinform');
handleEvent(signInForm, 'submit', e => {
e.preventDefault();
if(!isEmpty(signInForm)){
signInUsername = getElement('input[name="username"]', signInForm).value;
signInPassword = getElement('input[name="password"]', signInForm).value;
recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;
if(recaptchaV3){
signInData = new FormData();
signInData.append('username', signInUsername);
signInData.append('password', signInPassword);
signInData.append('recaptchav3', recaptchaV3);
isLogened = request('POST', '/signin', signInData);//, 'dashboard');
isLogened.then(result => {
checkCookie(result.access_token);
return window.location.href = 'dashboard';
}, result => {
log('Cant get response')
});
} else{
alert('Перезагрузите страницу');
}
}
})

Python to C# can't understand requests.put(url,data=...)

I can't figure out the image data send error, not familiar with JSON.
Given this working Python code:
def uploadImage(image_name, folder_path, location):
path = folder_path + '\\' + image_name
with open(path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
req_body = {"filename": image_name, "location": location}
resp_post = requests.post( "myURL", json=req_body)
if resp_post.status_code == 200:
url = resp_post_json = resp_post.json()['url'] # facing c# problem here
resp_put = requests.put(url,data=encoded_string)
if resp_put.status_code != 200:
return "PUT request error : {}".format(resp_put.reason)
else:
retur
"POST request error : {}".format(resp_post.reason)
C# code:
internal void UploadImage(string strImagePathNName, string strImageName, string strLoaction)
{
try
{
// read file in base 64 string
string base64String = Convert.ToBase64String(File.ReadAllBytes(strImagePathNName));
if (base64String.Length > 0)
{
var webAddr = "myURL";
string json = "{\"filename\":\"" + strImageName + "\"," + "\"location\":\"" + strLoaction + "\"}";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
}
bool bIsGotResponseFromServer = false;
var strResponseUri = string.Empty;
using (HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
using (Stream respStream = webResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
strResponseUri = reader.ReadToEnd();
UrlFromJson myojb = (UrlFromJson)JsonConvert.DeserializeObject(strResponseUri, typeof(UrlFromJson));
strResponseUri = myojb.url; //retrieved the URl
bIsGotResponseFromServer = true;
}
}
}
if (bIsGotResponseFromServer)
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(strResponseUri);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "post";
json = "{\"data\":\"" + base64String + "\"}";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json); /// not sure about this line
streamWriter.Close();
}
using (HttpWebResponse webResponse1 = (HttpWebResponse)httpWebRequest.GetResponse()) // received error here
{
if (webResponse1.StatusCode == HttpStatusCode.OK)
{
}
}
}
}
}
catch (WebException e)
{
}
}
Solution
Just using the base64 string instead of the httpWebRequest.GetRequestStream:
Stream.Write(base64String,0, base64String.Length);
and set:
httpWebRequest.Method = "PUT";

Graphql query in Python

Here is a graphql query with its result : OK.
I try to get the same result with Python, but I get nothing : response.text is empty. (API key is not needed).
q = """
{
node(id: "UXVlc3Rpb25uYWlyZTo5NTNjYjdjYS0xY2E0LTExZTktOTRkMi1mYTE2M2VlYjExZTE=") {
... on Questionnaire {
replies(first: 10, after: null) {
totalCount
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
createdAt
publishedAt
updatedAt
author {
id
}
responses {
question {
title
}
... on ValueResponse {
value
}
}
}
}
}
}
}
}
"""
response = requests.post(url = "https://granddebat.fr/graphql" , json = {'query': q})
print(response.text)
Please, any idea ?
It's all good with the query itself. In request you need to pass headers with {'Accept':
'application/vnd.cap-collectif.preview+json'}
response = requests.post(
url = "https://granddebat.fr/graphql",
json = {'query': q,},
headers= {'Accept': 'application/vnd.cap-collectif.preview+json'}
)

Categories

Resources