GetResponse throws 400 Bad request - c#

Getting 400 bad Request When trying to get the Response from my HTTPS post request. Here is my code:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://coupons.valassis.eu/capi/directPrint/"+offerID);
httpWebRequest.Credentials = new NetworkCredential(userName,Password);
WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
myWebHeaderCollection.Add("Authorization: Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(httpWebRequest.Credentials.ToString())));
myWebHeaderCollection.Add("x-valassis-country-code: uk");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "[{ \"consumerId\": \"000000000000001\", \"remoteConsumerId\": \"000000000000001\" , \"Barcode\": \"Itf: 04910033400000000000000001,Ean13:ccode\", \"Type\": \"j\", \"returnUrl\": \"http://www.durex.co.uk\",\"CouponDescription\" : \"Coupon For:\"" + this.FirstName + " " + this.SurName + "\" }]";
var serializer = new JavaScriptSerializer();
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream streamReader =httpResponse.GetResponseStream())
{
using (StreamReader r = new StreamReader(streamReader))
{
var result = r.ReadToEnd();
}
}
}
}
catch (WebException e)
{
}
Any one knows what might be the problem? or How to solve this issue?

The JSON string that you create is invalid, as the CouponDescription property contains an odd number of quotes.
If i run this....
var FirstName = "Joe";
var SurName = "Bloggs";
var json = "[{ \"consumerId\": \"000000000000001\", \"remoteConsumerId\": \"000000000000001\" , \"Barcode\": \"Itf: 04910033400000000000000001,Ean13:ccode\", \"Type\": \"j\", \"returnUrl\": \"http://www.durex.co.uk\",\"CouponDescription\" : \"Coupon For:\"" + FirstName + " " + SurName + "\" }]";
I get...
[{ "consumerId": "000000000000001", "remoteConsumerId": "000000000000001" , "Barcode": "Itf: 04910033400000000000000001,Ean13:ccode", "Type": "j", "returnUrl": "http://www.durex.co.uk","CouponDescription" : "Coupon For:"Joe Bloggs" }]
Look at the CouponFor value, the quotes are not closed.
Tools like LINQPad and JSONLint are very useful for validating code snippets in these scenarios

Related

oauth 2.0 in c# getting 400 error unsure why

i am trying to fetch an access token by calling an API with an auth code and keeping getting a 400 error.
I have read many a web sites and can't see what is wrong with this. thanks. I have left in commented bits as this is other ways I have tried. Appreciate any quick advice
HttpWebRequest request = WebRequest.Create("https://identity.xero.com/connect/token") as HttpWebRequest;
request.Headers.Add("Authorization", "Basic " + b64_id_secret);
//string data = "{ grant_type : refresh_token, refresh_token : " + l_auth_code+ "}";
//string data = "{ 'grant_type' : 'authorization_code', 'code' : '" + l_auth_code + "', 'redirect_uri' : '" + C_XERO_REDIRECT_URL + "'}";
request.ContentType = "application/json";
request.Method = "POST";
//request.ContentType = "application/json";
//request.ContentLength = postBytes.Length;
//request.Accept = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"grant_type\":\"authorization_code\"," +
"\"code\":\"" + l_auth_code + "\","+
"\"redirect_uri\":\"" + C_XERO_REDIRECT_URL + "\"}";
streamWriter.Write(json);
}
// crashes here
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}

Getting System.IO.IOException in mscorlib.dll

i try to make an HTTP POST to an Swagger UI api and wrote this rudimentary Code:
string baseip = "192.168.0.1";
string auth = "authcodre";
string name = "TestMan";
string ip = "1.1.1.1";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string URL = "https://" + baseip + ":4444/api/objects/network/host/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.ContentType = "application/json";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("token:" + auth));
request.PreAuthenticate = true;
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string patchtxt = "{ \"name\": \"" + name + "\", \"_type\": \"network/host\", \"address\": \"" + ip + "\"}";
streamWriter.Write(patchtxt);
streamWriter.Flush();
streamWriter.Close();
Console.WriteLine("Patches");
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); //Einlesen der HTTP-Antwort
string resppatch = reader.ReadToEnd();
Console.WriteLine(resppatch);
Console.ReadLine();
}
It throws me an System.IO.IOException" in mscorlib.dll at this line:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
Can anyone explain why this happens and how to fix it?
Thank you :)

Deserializing HttpWebResponse from JSON API in c#

I know that such of these topics existing a lot here on stackoverflow.
But I have a little bit different problem:
I have created a DataContract Class like below:
[DataContract]
public class GLSParcelClass {
internal string Location;
internal string ConsignmentId;
internal string Labels;
internal List<Parcels> ParcelList;
internal List<Returns> ReturnList;
}
[DataContract]
public class Parcels {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
[DataContract]
public class Returns {
internal string Location;
internal string TrackId;
internal string ParcelNumber;
}
Then I wrote the following function:
WebRequest httpWebRequest = WebRequest.Create(this.GLSUri);
string json = "{" +
"\"shipperId\":\"2764200001 276a165X14\"," +
"\"references\":[\"47110815\"]," +
"\"addresses\":{" +
"\"delivery\":{" +
"\"name1\":\"Max Meyer\"," +
"\"name2\":\"Meyer Ltd.\"," +
"\"street1\":\"Meyer Str. 227\"," +
"\"street2\":\"2. Floor\"," +
"\"country\":\"DE\"," +
"\"zipCode\":\"92753\"," +
"\"city\":\"Passau\"," +
"\"email\":\"maxmeyer#gmail.com\"}}," +
"\"parcels\":[" +
"{" +
"\"weight\":2.5," +
"\"references\":[" +
"\"47110815\"]" +
"}" +
"]" +
"}";
httpWebRequest.ContentType = "application/json";
Type type = httpWebRequest.Headers.GetType();
System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
System.Reflection.MethodInfo m = type.GetMethod("AddWithoutValidate", flags);
m.Invoke(httpWebRequest.Headers, new string[] { "Accept", "application/json" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Language", "de" });
m.Invoke(httpWebRequest.Headers, new string[] { "Accept-Encoding", "gzip,deflate" });
httpWebRequest.Method = "POST";
string lsEncodedCred = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("utf-8").GetBytes("shipmentsapi" + ":" + "shipmentsapi"));
httpWebRequest.Headers.Add("Authorization", "Basic " + lsEncodedCred);
httpWebRequest.PreAuthenticate = true;
StreamWriter streamWriter = null;
using (streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) {
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader loStream = new StreamReader(httpResponse.GetResponseStream())) {
GLSParcelClass deserializedParcels = new GLSParcelClass();
string lsJSON = loStream.ReadToEnd();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(lsJSON));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedParcels.GetType());
deserializedParcels = ser.ReadObject(ms) as GLSParcelClass;
ms.Close();
}
I got the answer "Created" with status code 201 from the JSON API in the response header. So far so good. But when I will get the ResponseStream I get the error "System.Runtime.Serialization.SerializationException - Error while deserializing the object. Unexpected char ".".".
Alternative I have tested it with the Mozilla REST client. And I will get the correct header with a correct response stream.
The response stream included also a base64 string encoded pdf document.
I really don't know what's wrong and I hope you can help me.
Thx a lot in advance.
Milo
I just be able to post a very small part of the JSON response as on the screenshot:
JSON response part
If I'm opening the JSON quick view at the monitoring window, I just get the message back "string is not JSON formated".
Milo

Posting tasks to asana through API stopped working

I wrote a program to post tasks to asana through the API and it has been working fine up until this morning, can anyone help me figure out why that is?
this is an example of the JSON string I am sending:
{"workspace":09876543321111,"data": {"assignee":null,"name":"Sample Name","notes":"Sample Noted","due_on":"2015-01-27","projects":"12434567889099","completed":false}}
and I am getting a 400 error: bad request.
this is my code:
string ID = "09876543321111"; //workspace ID
string url = #"https://app.asana.com/api/1.0/workspaces/" + ID + #"/tasks";
Data dat = new Data();
string ProjName = "Test Project";
dat.projects = "1234567890234";
dat.assignee = null;
dat.name = "Sample Name";
dat.notes = "Sample Notes";
dat.due_on = val.requiredBy.Value.ToString("u").Substring(0, 10);
dat.completed = false;
//if task doesnt exist, make one
if (!Tasks.CheckExist(project, dat.projects, dat.name, apiKey, log))
{
string json = JsonConvert.SerializeObject(dat);
string data = "{\"workspace\":" + ID + ",\"data\": " + json + "}";
log.WriteLine(data);
Functions.Post(data, url, apiKey, log);
}
Post function:
//post tasks to asana
public static void Post(string data, string url, string apiKey, StreamWriter log)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = bytes.Length;
req.ContentType = "application/json";
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization: Basic " + encodedAuthInfo);
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
catch (WebException ex)
{
HttpWebResponse response = ((HttpWebResponse)ex.Response);
string exc = url + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription;
Console.WriteLine(exc);
log.WriteLine(exc);
}
}
EDIT
for anyone who cares I solved the problem by changing string data to:
string data = "{\"data\": " + json + "}";
We recently made a change to return a 400 error if there were unexpected parameters passed at the top level, as (nearly) all API routes only use the parameters passed in under the "data" attribute. In this case (as you correctly determined) the "workspace" attribute at the top level was incorrect - previously we just ignored it, but in an effort to make the API less "surprising" we wanted to be explicit and strict about parameters that could be ignored, as otherwise it could be misleading.

C# HttpWebRequest to Scorm Cloud always returning error 400 bad request

I am trying to post Tin Can Statements to a Scorm Cloud LRS via c# HttpWebRequest in JSON format. However I always get error 400. The authentication is correct so what is wrong with the JSON? I have tried encoding as UTF8 also and still no dice
Here is the code and credentials needed:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://cloud.scorm.com/ScormEngineInterface/TCAPI/RCFZ5D8GXU/sandbox/");
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Method = "POST";
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
String autorization= "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("RCFZ5D8GXU222" + ":" + "YQA3VfX1NiuYkKXEEzkKu723NwejpwNkB6x0Vhg3"));
httpWebRequest.Headers.Add("Authorization", autorization);
httpWebRequest.Headers.Add("X-Experience-API-Version", "1.0.1");
string jsonText = "{"+
" \"actor\": {"+
" \"mbox\": \"mailto:Steeno#gmail.com\","+
" \"name\": \"Austin Glatt\","+
" \"objectType\": \"Agent\""+
"},"+
"\"verb\": {"+
" \"id\": \"http://adlnet.gov/expapi/verbs/attempted\","+
" \"display\": {"+
" \"en-US\": \"attempted\""+
" }"+
"},"+
"\"object\": {"+
" \"id\": \"http://www.example.com/tincan/activities/cMjKwAGI\","+
" \"objectType\": \"Activity\","+
" \"definition\": {"+
" \"name\": {"+
" \"en-US\": \"Part Removal\""+
" },"+
" \"description\": {"+
" \"en-US\": \"On Engine 155\""+
" }"+
" }"+
"}"+
"}";
byte [] jsonData = System.Text.Encoding.UTF8.GetBytes(jsonText);
Debug.Log(System.Text.Encoding.UTF8.GetString(jsonData));
httpWebRequest.ContentLength = jsonData.Length;
using (var streamWriter = httpWebRequest.GetRequestStream())
{
streamWriter.Write(jsonData,0,jsonData.Length);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Debug.Log("POST result"+result);
}
}
catch(WebException ex)
{
if (ex.Response != null)
{
Debug.Log(ex.Message);
foreach(DictionaryEntry d in ex.Data)
Debug.Log(d.ToString());
string errorDetail = string.Empty;
using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream(), true))
{
errorDetail = streamReader.ReadToEnd();
Debug.Log(errorDetail);
}
}
}
I think you are missing the "statements" on the URL, your request should be going to:
https://cloud.scorm.com/ScormEngineInterface/TCAPI/RCFZ5D8GXU/sandbox/statements
Original answer in case anyone cares:
It appears you are posting a 0.95 or 1.0.x statement, but you don't seem to be setting an X-Experience-API-Version header, so the LRS is probably interpreting it as a 0.9 statement which would be invalid.
I'd highly recommend using a library to build the requests along with the content of the request. We have one available here:
http://rusticisoftware.github.io/TinCan.NET/

Categories

Resources