0

I am trying to make a post request, but keep getting error 400 Bad Request in the response.

The request is to upload a pdf file for a customer. The example provided in the documentation is a curl command and i'm having difficulty recreating it in C#

This is the curl example:

curl -F "metadata=<test.json" -F "[email protected]" https://api.company.com/v1/documents/customer/customer-<Customer's GUID>/upload?authentication=<token>;

In the test.json file it stores the document name, type, category and description. (JSON format).

Here is my C# code

 byte[] pdfFile = File.ReadAllBytes(document path);
 string document = Convert.ToBase64String(pdfFile);

 Document docToUpload = new Document();
 docToUpload.name = "testDoc";
 docToUpload.format = "PDF";
 docToUpload.description = "this is a test";
 docToUpload.category = "19";

 List<Document> docs = new List<Document>();
 docs.Add(docToUpload);

 DocumentObjects docObject = new DocumentObjects();
 docObject.document = docs;

 //convert object to JSON 
 string postData = JsonConvert.SerializeObject(docObject);

  WebRequest docRequest = WebRequest.Create("https://api.company.com/v1/documents/customer/customer-"+customerGuid+"/upload?authentication=" + token);

  using (var streamWriter = new StreamWriter(docRequest.GetRequestStream()))
  {
     streamWriter.Write(postData);
  }

  var responsedoc = (HttpWebResponse)docRequest.GetResponse();

  using (var streamReader = new StreamReader(responsedoc.GetResponseStream()))
  {
    result = streamReader.ReadToEnd();
    Console.WriteLine(result);
  }
7
  • Is "<Customer's GUID>" suppose to be there instead of a unique Guid? Commented Apr 11, 2017 at 4:32
  • It's a unique guide to represent the customer. The "token" is also a unique identifier. Commented Apr 11, 2017 at 11:35
  • in your code it does not seem like it is unique. You are adding "<Customer's GUID>" directly in the link and not the specific guid like you did with token.. Commented Apr 11, 2017 at 11:38
  • Sorry for the confusion. I was just using <customer's guid> as a place holder in the question. I'm actually passing the real guid. Commented Apr 11, 2017 at 12:05
  • Try using HttpWebRequest instead of WebRequest. (HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"api.company.com/v1/documents/customer/…" + token); Also use UserAgent: req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; Commented Apr 11, 2017 at 12:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.