locked
Make a web service request and read response from example cUrl RRS feed

  • Question

  • User-235682625 posted

    Hi,

    I have an below example of cURL command, i want to make a similar webservice request using .NET Can someone please help me convert below curl to .NET request.

    Thanks in advance.

    curl -H 'X-API-TOKEN: yourapitoken' -H "Expects:" \
      -F 'surveyId=SV_012345678912345' \
      -F 'file=@example.csv;type=text/csv' \
      'https://yourdatacenterid.qualtrics.com/API/v3/responseimports'
    Wednesday, June 21, 2017 3:41 PM

All replies

  • User991499041 posted

    Hi renu.paldiwal,

    You'd use one of the following options:

    HttpWebRequest/HttpWebResponse
    WebClient
    HttpClient (available from .NET 4.5 on)

    I'd highly recommend using the HttpClient class, as it's engineered to be much better. You could also use HttpWebRequest/HttpWebResponse, check this answer.

    using (var client = new HttpClient())
    {
    	var url = "https://xxx";
    	client.DefaultRequestHeaders.Add("name", "value");
    	...
    	var response =  client.GetStringAsync(url);
        
    }

    Regards,

    zxj

    Thursday, June 22, 2017 2:37 AM
  • User1967761114 posted

    Hi renu.paldiwal,

    According to your description, you could refer to the following code.

    var request = System.Net.HttpWebRequest.Create("https://yourdatacenterid.qualtrics.com/API/v3/responseimports");
    request.Headers.Add("X-API-TOKEN", "yourapitoken");
    request.Headers.Add("Expects");
    request.Method = "POST";
    var boundary = DateTime.Now.Ticks.ToString("x");
    request.ContentType = "multipart/form-data; boundary=" + boundary;
    var filePath = "D:\\1.txt";
    Stream requestStream = request.GetRequestStream();
    if (System.IO.File.Exists(filePath))
    {
        boundary = "--" + boundary;
        //surveyId
        string data = boundary + "\r\nContent-Dis-data; name=\"surveyId\";\r\n\r\nSV_012345678912345\r\n";
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(data);
        requestStream.Write(formitembytes, 0, formitembytes.Length);
        //file
        data = boundary + "\r\nContent-Dis-data; name=\"file\";filename=\"" + Path.GetFileName(filePath) + "\"\r\nContent-Type:application/octet-stream\r\n\r\n";
        formitembytes = System.Text.Encoding.UTF8.GetBytes(data);
        requestStream.Write(formitembytes, 0, formitembytes.Length);
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                requestStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
        }
        //end
        formitembytes = System.Text.Encoding.UTF8.GetBytes("\r\n" + boundary + "--");
        requestStream.Write(formitembytes, 0, formitembytes.Length);
    }
    request.ContentLength = requestStream.Length;
    requestStream.Close();
    //get response
    var reponse = request.GetResponse();

     

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Thursday, June 22, 2017 2:39 AM
  • User-235682625 posted

    Even,

    first of all thank you for the detailed code, I tried to implement this but i am still getting operation timeout error; Please see below the code I implemented.

     var request = System.Net.HttpWebRequest.Create("https://yourdatacenterid.qualtrics.com/API/v3/responseimports");
                request.Headers.Add("X-API-TOKEN: xxxxxxxxxxxxxx");
                //request.Headers.Add("Expects");
                request.Method = "POST";
                var boundary = DateTime.Now.Ticks.ToString("x");
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                var filePath = "C:\\test.csv";
                Stream requestStream = request.GetRequestStream();
                if (System.IO.File.Exists(filePath))
                {
                    boundary = "--" + boundary;
                    //surveyId
                    string data = boundary + "\r\nContent-Dis-data; name=\"surveyId\";\r\n\r\nSV_ePswPpv4rPD77fL5\r\n";
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(data);
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                    //file
                    data = boundary + "\r\nContent-Dis-data; name=\"file\";filename=\"" + Path.GetFileName(filePath) + "\"\r\nContent-Type:application/octet-stream\r\n\r\n";
                    formitembytes = System.Text.Encoding.UTF8.GetBytes(data);
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        byte[] buffer = new byte[1024];
                        int bytesRead = 0;
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                        }
                        fileStream.Close();
                    }
                    //end
                    formitembytes = System.Text.Encoding.UTF8.GetBytes("\r\n" + boundary + "--");
                    requestStream.Write(formitembytes, 0, formitembytes.Length);
                }
                //request.ContentLength = requestStream.Length;
                requestStream.Close();
                //get response
                var reponse = request.GetResponse();

    I also got a Node.JS script for the same which is working fine , i have attached the screenshot of Node.js script is there a way we can convert this Node.js script to C#.

    var request = require('request');
    var fs = require('fs');
    var url = "https://yourdatacenterid.qualtrics.com/API/v3/responseimports";
    var surveyId = "SV_ePswPpv4rPD77fL";
    var token="XXXYourTokeXX";
    var formdata={
    	surveyId:surveyId,
    	file: fs.createReadStream("test.csv")
    };
    
    var options={
    	header:{
    		'content-type':'multipart/form-data',
    		'X-API-TOKEN':token
    	},
    	method:"POST",
    	url:url,
    	formdata: formdata
    };
    
    request(options,function(error,response,body){
    	if(error)
    	{
    		
    		console.log("Error" +error)
    	}
    	else{
    		console.log(response.body);
    	}
    		
    }



    Thursday, June 22, 2017 3:07 PM
  • User1967761114 posted

    Hi renu.paldiwal,

    I rewrite my code, and I test succeeds this time, see the following code:

    public string HttpPostData(string url, string fileKeyName, string filePath, NameValueCollection stringDict)
    {
        var memStream = new MemoryStream();
        var webRequest = (HttpWebRequest)WebRequest.Create(url);
        var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
        var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
        webRequest.Method = "POST";
        webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
        const string filePartHeader =
            "Content-Dis-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
             "Content-Type: application/octet-stream\r\n\r\n";
        var header = string.Format(filePartHeader, fileKeyName, filePath);
        var headerbytes = Encoding.UTF8.GetBytes(header);
        memStream.Write(beginBoundary, 0, beginBoundary.Length);
        memStream.Write(headerbytes, 0, headerbytes.Length);
        var buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        var stringKeyHeader = "\r\n--" + boundary +
                               "\r\nContent-Dis-data; name=\"{0}\"" +
                               "\r\n\r\n{1}\r\n";
        foreach (byte[] formitembytes in from string key in stringDict.Keys
                                         select string.Format(stringKeyHeader, key, stringDict[key])
                                             into formitem
                                         select Encoding.UTF8.GetBytes(formitem))
        {
            memStream.Write(formitembytes, 0, formitembytes.Length);
        }
        memStream.Write(endBoundary, 0, endBoundary.Length);
        webRequest.ContentLength = memStream.Length;
        var requestStream = webRequest.GetRequestStream();
        memStream.Position = 0;
        var tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);
        memStream.Close();
        requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        requestStream.Close();
        string responseContent;
        var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
        using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                        Encoding.GetEncoding("utf-8")))
        {
            responseContent = httpStreamReader.ReadToEnd();
        }
        fileStream.Close();
        httpWebResponse.Close();
        webRequest.Abort();
        return responseContent;
    }

    You could invoke it such like the following code:

    var datas = new NameValueCollection();
    datas.Add("surveyId", "nSV_ePswPpv4rPD77fL5");
    HttpPostData("https://yourdatacenterid.qualtrics.com/API/v3/responseimports", "file", "C:\\test.csv", datas);

     

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Friday, June 23, 2017 10:04 AM
  • User-235682625 posted

    this is not working and does not have an API token, I am getting the same error, I tried to do the same call using Node.JS script below and It works perfectly fine, I believe we need to convert the below Node.JS script to c# .

    var request = require('request');
    var fs = require('fs');
    var url = "https://yoururl/API/v3/responseimports";
    var surveyId = "SV_ePswPpv4rPD77fL";
    var token="AXXXXXXXXXXXXXZZZZ";
    var formData={
    	surveyId:surveyId,
    	file: fs.createReadStream("test.csv")
    };
    
    var options = {
    	headers:{
    		'content-type':'multipart/form-data',
    		'X-API-TOKEN':token
    	},
    	method:"POST",
    	url:url,
    	formData: formData
    };
    
    request(options, function(error,response,body){
    	if(error){
    		console.log("Error" +error);
    	}
    	else{
    		console.log(response.body);
    		console.log("webservice call completed");
    		console.log(response.statusCode);
    
    	}
    		
    });

    Friday, June 23, 2017 3:43 PM
  • User991499041 posted

    Hi Renu,

    You can check below Full HTTP POST/WebRequest Example (C#) and CSV file.

    class Program
    {
    static void Main(string[] args)
    {
    string URLAuth = "***urlauth***";
    WebClient webClient = new WebClient();
    
    NameValueCollection formData = new NameValueCollection();
    formData["Username"] = "myUser";
    formData["Password"] = "myPassword";
    
    byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", formData);
    string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);
    webClient.Dispose();
    
    string URL = "***url***";
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
    System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
    
    webRequest.Method = "POST";
    webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    
    string FilePath = "C:\\test.csv";
    formData.Clear();
    formData["ticket"] = resultAuthTicket;
    formData["ReplaceAll"] = "false";
    
    Stream postDataStream = GetPostStream(FilePath, formData, boundary);
    
    webRequest.ContentLength = postDataStream.Length;
    Stream reqStream = webRequest.GetRequestStream();
    
    postDataStream.Position = 0;
    
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    
    while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
    {
    reqStream.Write(buffer, 0, bytesRead);
    }
    
    postDataStream.Close();
    reqStream.Close();
    
    StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
    string Result = sr.ReadToEnd();
    }
    
    private static Stream GetPostStream(string filePath, NameValueCollection formData, string boundary)
    {
    Stream postDataStream = new System.IO.MemoryStream();
    
    //adding form data
    string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
    "Content-Dis-data; name=\"{0}\";" + Environment.NewLine + Environment .NewLine + "{1}";
    
    foreach (string key in formData.Keys)
    {
    byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,
    key, formData[key]));
    postDataStream.Write(formItemBytes, 0, formItemBytes.Length);
    }
    
    //adding file data
    FileInfo fileInfo = new FileInfo(filePath);
    
    string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
    "Content-Dis-data; name=\"{0}\"; filename=\"{1}\"" +
    Environment.NewLine + "Content-Type: application/vnd.ms-excel" + Environment.NewLine + Environment.NewLine;
    
    byte[] fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate,
    "UploadCSVFile", fileInfo.FullName));
    
    postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
    
    FileStream fileStream = fileInfo.OpenRead();
    
    byte[] buffer = new byte[1024];
    
    int bytesRead = 0;
    
    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
    postDataStream.Write(buffer, 0, bytesRead);
    }
    
    fileStream.Close();
    
    byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--");
    postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
    
    return postDataStream;
    }
    }

    Regards,

    zxj

    Tuesday, June 27, 2017 7:18 AM