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 "payload=@test.pdf" 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);
  }
Panthr073
  • 13
  • 1
  • 5
  • Is "" suppose to be there instead of a unique Guid? – Christopher Smit Apr 11 '17 at 04:32
  • It's a unique guide to represent the customer. The "token" is also a unique identifier. – Panthr073 Apr 11 '17 at 11:35
  • in your code it does not seem like it is unique. You are adding "" directly in the link and not the specific guid like you did with token.. – Christopher Smit Apr 11 '17 at 11:38
  • Sorry for the confusion. I was just using as a place holder in the question. I'm actually passing the real guid. – Panthr073 Apr 11 '17 at 12:05
  • Try using HttpWebRequest instead of WebRequest. (HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(@"https://api.company.com/v1/documents/customer/customer-"+customerGuid+"/upload?authentication=" + 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)"; – Christopher Smit Apr 11 '17 at 12:26
  • One of the issues that I am having is that I do not understand how to pass both JSON data and a pdf file all at once. – Panthr073 Apr 11 '17 at 13:27
  • Try looking at this question: http://stackoverflow.com/questions/11345382/convert-object-to-json-string-in-c-sharp – Christopher Smit Apr 12 '17 at 04:19

0 Answers0