Matlab urlread2 - HTTP response code: 415 for URL - matlab

I am attempting to access the betfair API using Matlab and the urlread2 function available here.
EDIT: I have posted this problem on Freelancer if anyone can help with it: tinyurl.../pa7sblb
The documentation for the betfair API I am following is this getting started guide. I have successfully logged in and kept the session open using these codes: (I am getting a success response)
%% Login and get Token
url = 'https://identitysso.betfair.com/api/login';
params = {'username' '******' 'password' '******'};
header1 = http_createHeader('X-Application','*****');
header2 = http_createHeader('Accept','application/json');
header = [header1, header2];
[paramString] = http_paramsToString(params)
[login,extras] = urlread2(url,'POST',paramString,header)
login = loadjson(login)
token = login.token
%% Keep Alive
disp('Keep Session Alive')
url_alive = 'https://identitysso.betfair.com/api/keepAlive';
header1 = http_createHeader('X-Application','******');
header2 = http_createHeader('Accept','application/json');
header3 = http_createHeader('X-Authentication',token');
header_alive = [header1, header2, header3];
[keep_alive,extras] = urlread2(url_alive,'POST',[],header_alive);
keep_alive = loadjson(keep_alive);
keep_alive_status = keep_alive.status
My trouble starts when I am attempting to do the next step and load all available markets. I am trying to replicate this example code which is designed for Python
import requests
import json
endpoint = "https://api.betfair.com/exchange/betting/rest/v1.0/"
header = { 'X-Application' : 'APP_KEY_HERE', 'X-Authentication' : 'SESSION_TOKEN_HERE' ,'content-type' : 'application/json' }
json_req='{"filter":{ }}'
url = endpoint + "listEventTypes/"
response = requests.post(url, data=json_req, headers=header)
The code I am using for Matlab is below.
%% Get Markets
url = 'https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/';
header_application = http_createHeader('X-Application','******');
header_authentication = http_createHeader('X-Authentication',token');
header_content = http_createHeader('content_type','application/json');
header_list = [header_application, header_authentication, header_content];
json_body = savejson('','filter: {}');
[list,extras] = urlread2(url_list,'POST',json_body,header_list)
I am having trouble with a http response code 415. I believe that the server cannot understand my parameter since the headings I have used with success previously.
Any help or advice would be greatly appreciated!
This is the error:
Response stream is undefined
below is a Java Error dump (truncated):
Error using urlread2 (line 217)
Java exception occurred:
java.io.IOException: Server returned HTTP response code: 415 for URL....

I looked at your problem and it seems to be caused by two things:
1) The content type should be expressed as 'content-type' and not 'content_type'
2) The savejson-function doesn't create an adequate json-string. If you use the json-request from the Python-script it works.
This code work for me:
%% Get Markets
url = 'https://api.betfair.com/exchange/betting/rest/v1.0/listEventTypes/';
header_application = http_createHeader('X-Application','*********');
header_authentication = http_createHeader('X-Authentication',token');
header_content = http_createHeader('content-type','application/json');
header_list = [header_application, header_authentication, header_content];
json_body = '{"filter":{ }}';
[list,extras] = urlread2(url,'POST',json_body,header_list)

Related

Why i am getting authentication error in MATLAB while i try to use HTTP

I am trying to query SiriDB via Matlab. I am getting the positive response from my log-in attemps. However when i try to query, i get the error: "not authenticated".
Please see my code below:
clear;clc
import matlab.net.http.*
import matlab.net.http.field.*
import matlab.net.URI
import matlab.net.http.Credentials
strct1 = jsondecode('{"username": "my_user_name", "password": "my_password"}');
strct2 = jsondecode('{"query": "select last() from ''example_query''"}');
uri = 'http://example_adress/auth/login';
request = RequestMessage( 'POST',ContentTypeField( 'application/json'),strct1);
complete(request,uri);
response = send(request,uri);
complete(response);
response.Body.string
uri = 'http://example_api';
request = RequestMessage( 'POST',ContentTypeField( 'application/json'),strct2 );
complete(request,uri)
response = request.send( 'http://example_api' );
complete(response);
response.Body.string

Text to Speech enableTimePointing not working in Python

Using texttospeech_v1beta1 to get ssml_mark but getting
"TypeError: synthesize_speech() got an unexpected keyword argument
'enableTimePointing'" error.
from google.cloud import texttospeech_v1beta1
client = texttospeech_v1beta1.TextToSpeechClient()synthesis_input = texttospeech_v1beta1.SynthesisInput(ssml=text)
voice = texttospeech_v1beta1.VoiceSelectionParams(language_code='tr-TR',name='tr-TR-Wavenet-E')
audio_config = texttospeech_v1beta1.AudioConfig(
audio_encoding=texttospeech_v1beta1.AudioEncoding.MP3)
response = client.synthesize_speech(input=synthesis_input, voice=voice, audio_config=audio_config, enableTimePointing = 'SSML_MARK')
print(response.timepoints)
You need to create a SynthesizeSpeechRequest Object instead of passing the arguments individually into client.synthesize_speech
So,
request = texttospeech_v1beta1.SynthesizeSpeechRequest(
input=synthesis_input,
voice=voice,
audio_config=audio_config,
enable_time_pointing=[texttospeech_v1beta1.SynthesizeSpeechRequest.TimepointType.SSML_MARK]
response = client.synthesize_speech(request)
Full example
from google.cloud.texttospeech_v1beta1 import VoiceSelectionParams, AudioConfig, AudioEncoding, SynthesizeSpeechRequest, SynthesisInput, TextToSpeechClient
client = TextToSpeechClient()
synthesis_input = SynthesisInput(ssml="<speak><mark name=\"1st\"/>Hello <mark name=\"2nd\"/>world</speak>")
voice = VoiceSelectionParams(language_code='en-US', name='en-US-Wavenet-D', ssml_gender='MALE')
audio_config = AudioConfig(audio_encoding=AudioEncoding.MP3)
request = SynthesizeSpeechRequest(input=synthesis_input, voice=voice, audio_config=audio_config, enable_time_pointing=[SynthesizeSpeechRequest.TimepointType.SSML_MARK])
response = client.synthesize_speech(request=request)
timepoints = list(response.timepoints)
# do something with timepoints

get_process_lines in liquidsoap 1.3.0

I've just updated Liquidsoap to 1.3.0 and now get_process_lines does not return anything.
def get_request() =
# Get the URI
lines = get_process_lines("curl http://localhost:3000/api/v1/liquidsoap/next/my-radio")
log("liquidsoap curl returns #{lines}")
uri = list.hd(default="",lines)
log("liquidsoap will try and play #{uri}")
# Create a request
request.create(uri)
end
I read on the CHANGELOG
- Moved get_process_lines and get_process_output to utils.liq, added optional env parameter
Does it mean I have to do something to use utils.liq in my script now ?
The full script is as follows
set("log.file",false)
set("log.stdout",true)
set("log.level",3)
def apply_metadata(m) =
title = m["title"]
artist = m["artist"]
log("Now playing: #{title} by #{artist}")
end
# Our custom request function
def get_request() =
# Get the URI
lines = get_process_lines("curl http://localhost:3000/api/v1/liquidsoap/next/my-radio")
log("liquidsoap curl returns #{lines}")
uri = list.hd(default="",lines)
log("liquidsoap will try and play #{uri}")
# Create a request
request.create(uri)
end
def my_safe(s) =
security = sine()
fallback(track_sensitive=false,[s,security])
end
s = request.dynamic(id="s",get_request)
s = on_metadata(apply_metadata,s)
s = crossfade(s)
s = my_safe(s)
# We output the stream to an icecast
# server, in ogg/vorbis format.
log("liquidsoap starting")
output.icecast(
%mp3(id3v2=true,bitrate=128,samplerate=44100),
host = "localhost",
port = 8000,
password = "PASSWORD",
mount = "myradio",
genre="various",
url="http://www.myradio.fr",
description="My Radio",
s
)
Of course the API is working
$ curl http://localhost:3000/api/v1/liquidsoap/next/my-radio
annotate:title="Chamakay",artist="Blood Orange",album="Cupid Deluxe":http://localhost/stream/3.mp3
A more simple example :
lines = get_process_lines("echo hi")
log("lines = #{lines}")
line = list.hd(default="",lines)
log("line = #{line}")
returns the following logs
2017/05/05 15:24:42 [lang:3] lines = []
2017/05/05 15:24:42 [lang:3] line =
Many thanks in advance for your help !
geoffroy
The issue was fixed in liquidsoap 1.3.1
Fixed:
Fixed run_process, get_process_lines, get_process_output when compiling with OCaml <= 4.03 (#437, #439)
https://github.com/savonet/liquidsoap/blob/1.3.1/CHANGES#L12

How to log in to a website with urllib?

I am trying to log on this website: http://www.broadinstitute.org/cmap/index.jsp. I am using python 3.3 on Windows. I followed this answer https://stackoverflow.com/a/2910487/651779. My code:
import http.cookiejar
import urllib
url = 'http://www.broadinstitute.org/cmap/index.jsp'
values = {'j_username' : 'username',
'j_password' : 'password'}
data = urllib.parse.urlencode(values)
binary_data = data.encode('ascii')
cookies = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPRedirectHandler(),
urllib.request.HTTPHandler(debuglevel=0),
urllib.request.HTTPSHandler(debuglevel=0),
urllib.request.HTTPCookieProcessor(cookies))
response = opener.open(url, binary_data)
the_page = response.read()
http_headers = response.info()
It runs without erros, however the html in the_page is just the log in page. How can I log onto this page?
The site is using a JSESSIONID cookie to create session since HTTP requests are stateless. When you're making your request, you're not getting that session id first.
I sniffed a session to log into that site using Fiddler and found that the POST is made to a different URL, but it has that JSESSIONID cookie set. So you need to make a get to the URL first, capture that cookie using the cookiehandler, then POST to this URL:
post_url = 'http://www.broadinstitute.org/cmap/j_security_check'
You don't need to save the HTTP GET request at all, you can simply call opener.open(url), then in your code change the response line to this:
response = opener.open(post_url, binary_data)
Also the payload was missing the submit method. Here's the whole thing with the changes I suggest:
import http.cookiejar
import urllib
get_url = 'http://www.broadinstitute.org/cmap/index.jsp'
post_url = 'http://www.broadinstitute.org/cmap/j_security_check'
values = urllib.parse.urlencode({'j_username': <MYCOOLUSERNAME>,
'j_password': <MYCOOLPASSSWORD>,
'submit': 'sign in'})
payload = bytes(values, 'ascii')
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(
urllib.request.HTTPRedirectHandler(),
urllib.request.HTTPHandler(debuglevel=0),
urllib.request.HTTPSHandler(debuglevel=0),
urllib.request.HTTPCookieProcessor(cj))
opener.open(get_url) #First call to capture the JSESSIONID
resp = opener.open(post_url, payload)
resp_html = resp.read()
resp_headers = resp.info()
Any other requests using the opener you created will re-use that cookie and you should be able to freely navigate the site.

The request was aborted: Could not create SSL/TLS secure channel.

I want to implement Paypal dodirect method for user can do payment directly on my website instead of redirecting to user
so for that i have added this URL as https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
and i am using following code
PayPalAPIAAInterfaceClient objpaypalapiaainterfaceclient = new PayPalAPIAAInterfaceClient("paypalapiaa");
CustomSecurityHeaderType objcustomsecurityheadertype = new CustomSecurityHeaderType();
objcustomsecurityheadertype.Credentials = new UserIdPasswordType();
objcustomsecurityheadertype.Credentials.Signature = "a8ft-8ji.2tzocnfshfjj4ahgxn4avlxzply8bmsbupxafkbty2--c6p";
objcustomsecurityheadertype.Credentials.Username = "fred_1350925179_biz_api1.gmail.com";
objcustomsecurityheadertype.Credentials.Password = "1350925199";
DoDirectPaymentReq objdodirectpaymentreq = new DoDirectPaymentReq();
objdodirectpaymentreq.DoDirectPaymentRequest = new DoDirectPaymentRequestType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = new DoDirectPaymentRequestDetailsType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentAction = new PaymentActionCodeType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentAction = PaymentActionCodeType.Sale;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails = new PaymentDetailsType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard = new CreditCardDetailsType();
//objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.InvoiceID = "1";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.IPAddress = Request.ServerVariables["remote_addr"].ToString();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardType = CreditCardTypeType.MasterCard;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal = new BasicAmountType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner = new PayerInfoType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName = new PersonNameType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.currencyID = CurrencyCodeType.USD;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address = new AddressType();
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.PaymentDetails.OrderTotal.Value = "120";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CreditCardNumber ="1111222233334444";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CVV2 = "258";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpMonth = 9;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.ExpYear = 2013;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Payer = "rahularyansharma#gmail.com";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.FirstName = "Shakti";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.PayerName.LastName = "Kapoor";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Street1 ="test address";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.CityName = "Atlanta";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.StateOrProvince = "ga";
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.Country = CountryCodeType.US;
objdodirectpaymentreq.DoDirectPaymentRequest.DoDirectPaymentRequestDetails.CreditCard.CardOwner.Address.PostalCode = "12345";
DoDirectPaymentResponseType objdodirectpaymentresponsetype = objpaypalapiaainterfaceclient.DoDirectPayment(ref objcustomsecurityheadertype, objdodirectpaymentreq);
now when i am run this code throwing followin exception
'
The request was aborted: Could not create SSL/TLS secure channel.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
You can confirm the SSL protocol for https://www.sandbox.paypal.com, using https://www.ssllabs.com/ssltest. The screenshot shows that it supports TLS 1.2 You will need to add the following two lines to your code at the point of making httpclient call:
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Sample:
The implementation should solve the problem.
Sorry, i cannot add this as a comment/question.
It seems like one of certificates for paypal is not in the trusted list.
Can you try download paypal root certificate and install it as trusted CA?
I think this two links can help you:
https://www.sslshopper.com/ssl-certificate-not-trusted-error.html
and
http://raysilvadotnet.wordpress.com/2014/02/13/problema-system-net-webexception-the-request-was-aborted-could-not-create-ssltls-secure-channel/
(sorry, cannot insert more than 2 links as normal links)
Also, please make sure you authenticating via login/password not certificate. If you are using certificate for API, you should follow last paragraph of this link