forked from SciSharp/BotSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultipartHttpClient.cs
More file actions
95 lines (81 loc) · 2.87 KB
/
MultipartHttpClient.cs
File metadata and controls
95 lines (81 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace BotSharp.Core.Engines.Dialogflow
{
public class MultipartHttpClient
{
private const string delimiter = "--";
private string boundary = "SwA" + DateTime.UtcNow.Ticks.ToString("x") + "SwA";
private HttpWebRequest request;
private BinaryWriter os;
public MultipartHttpClient(HttpWebRequest request)
{
this.request = request;
}
public void connect()
{
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.SendChunked = true;
request.KeepAlive = true;
os = new BinaryWriter(request.GetRequestStream(), Encoding.UTF8);
}
public void addStringPart(string paramName, string data)
{
WriteString(delimiter + boundary + "\r\n");
WriteString("Content-Type: application/json\r\n");
WriteString("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n");
WriteString("\r\n" + data + "\r\n");
}
public void addFilePart(string paramName, string fileName, Stream data)
{
WriteString(delimiter + boundary + "\r\n");
WriteString("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n");
WriteString("Content-Type: audio/wav\r\n");
WriteString("\r\n");
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesActuallyRead;
bytesActuallyRead = data.Read(buffer, 0, bufferSize);
while (bytesActuallyRead > 0)
{
os.Write(buffer, 0, bytesActuallyRead);
bytesActuallyRead = data.Read(buffer, 0, bufferSize);
}
WriteString("\r\n");
}
public void finish()
{
WriteString(delimiter + boundary + delimiter + "\r\n");
os.Close();
}
private void WriteString(string str)
{
os.Write(Encoding.UTF8.GetBytes(str));
}
public string getResponse()
{
try
{
var httpResponse = request.GetResponse() as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
return result;
}
}
catch (WebException we)
{
using (var stream = we.Response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
}
}