This commit is contained in:
tanghc
2019-05-15 14:53:43 +08:00
parent ca5855c149
commit d489bdb4ce
23 changed files with 532 additions and 124 deletions

View File

@@ -21,6 +21,7 @@ namespace SDKCSharp.Client
{
private static OpenConfig DEFAULT_CONFIG = new OpenConfig();
private const String ERROR_RESPONSE_KEY = "error_response";
private Dictionary<string, string> header = new Dictionary<string, string>();
@@ -137,6 +138,11 @@ namespace SDKCSharp.Client
string method = request.Method;
string dataName = this.dataNameBuilder.Build(method);
Dictionary<string, object> jsonObject = JsonUtil.ParseToDictionary(resp);
bool errorResponse = jsonObject.ContainsKey(ERROR_RESPONSE_KEY);
if (errorResponse)
{
dataName = ERROR_RESPONSE_KEY;
}
object data = jsonObject[dataName];
string jsonData = data == null ? "{}" : data.ToString();
T t = JsonUtil.ParseObject<T>(jsonData);

View File

@@ -131,6 +131,7 @@ namespace SDKCSharp.Client
}
}
/// <summary>
/// post请求并且文件上传
/// </summary>
@@ -141,77 +142,126 @@ namespace SDKCSharp.Client
/// <returns></returns>
public string PostFile(string url, Dictionary<string, string> form, Dictionary<string, string> header, List<UploadFile> files)
{
Encoding ENCODING_UTF8 = Encoding.UTF8;
HttpWebRequest request = CreateWebRequest(url, header);
request.Method = METHOD_POST;
// 分隔符
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
using (MemoryStream memoryStream = new MemoryStream())
// 请求流
var postStream = new MemoryStream();
#region Form表单请求内容
// 文件数据模板
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
// 文本数据模板
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
// 是否有上传文件
bool hasFile = files != null && files.Count > 0;
if (hasFile)
{
// 1.分界线
string boundary = string.Format("----{0}", DateTime.Now.Ticks.ToString("x")), // 分界线可以自定义参数
appendBoundary = string.Format("--{0}\r\n", boundary),
endBoundary = string.Format("\r\n--{0}--\r\n", boundary);
byte[] beginBoundaryBytes = ENCODING_UTF8.GetBytes(appendBoundary),
endBoundaryBytes = ENCODING_UTF8.GetBytes(endBoundary);
StringBuilder payload = new StringBuilder();
// 2.组装 上传文件附加携带的参数 到内存流中
if (form != null && form.Count > 0)
// 处理上传文件
foreach (var fileItem in files)
{
ICollection<string> keys = form.Keys;
foreach (string key in keys)
string formdata = null;
// 上传文件
formdata = string.Format(
fileFormdataTemplate,
fileItem.Name, //表单键
fileItem.FileName);
byte[] formdataBytes = null;
// 第一行不需要换行
if (postStream.Length == 0)
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", appendBoundary, key, form[key]);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
}
else
{
formdataBytes = Encoding.UTF8.GetBytes(formdata);
}
postStream.Write(formdataBytes, 0, formdataBytes.Length);
// 写入文件内容
if (fileItem.FileData != null && fileItem.FileData.Length > 0)
{
postStream.Write(fileItem.FileData, 0, fileItem.FileData.Length);
}
}
// 3.组装文件头数据体 到内存流中
foreach (UploadFile uploadFile in files)
}
// 处理文本字段
foreach (var fieldItem in form)
{
string formdata = null;
{
string boundaryBlock = string.Format("{0}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: application/octet-stream\r\n\r\n", appendBoundary, uploadFile.Name, uploadFile.FileName);
byte[] boundaryBlockBytes = ENCODING_UTF8.GetBytes(boundaryBlock);
memoryStream.Write(boundaryBlockBytes, 0, boundaryBlockBytes.Length);
memoryStream.Write(uploadFile.FileData, 0, uploadFile.FileData.Length);
// 上传文本
formdata = string.Format(
dataFormdataTemplate,
fieldItem.Key,
fieldItem.Value);
}
// 4.组装结束分界线数据体 到内存流中
memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
// 5.获取二进制数据,最终需要发送给服务器的数据
byte[] postBytes = memoryStream.ToArray();
// 6.HttpWebRequest 组装
HttpWebRequest webRequest = CreateWebRequest(url, header);
webRequest.Method = METHOD_POST;
webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
webRequest.ContentLength = postBytes.Length;
BindHeader(webRequest, header);
if (Regex.IsMatch(url, "^https://"))
byte[] formdataBytes = null;
// 第一行不需要换行
if (postStream.Length == 0)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
}
else
{
formdataBytes = Encoding.UTF8.GetBytes(formdata);
}
postStream.Write(formdataBytes, 0, formdataBytes.Length);
}
// 结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
#endregion
request.ContentLength = postStream.Length;
#region
if (postStream != null)
{
postStream.Position = 0;
// 直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
// 7.写入上传请求数据
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(postBytes, 0, postBytes.Length);
}
// 8.获取响应
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), ENCODING_UTF8))
{
string body = reader.ReadToEnd();
return body;
}
}
////debug
//postStream.Seek(0, SeekOrigin.Begin);
//StreamReader sr = new StreamReader(postStream);
//var postStr = sr.ReadToEnd();
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.UTF8))
{
return myStreamReader.ReadToEnd();
}
}
}
static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

View File

@@ -0,0 +1,11 @@
using System;
using Newtonsoft.Json;
namespace SDKCSharp.Model
{
public class DemoFileUploadModel
{
[JsonProperty("remark")]
public string Remark { get; set; }
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SDKCSharp.Client;
using SDKCSharp.Common;
using SDKCSharp.Model;
@@ -27,8 +28,9 @@ namespace SDKTest
public static void Main(string[] args)
{
TestGet();
TestCommon();
//TestGet();
//TestCommon();
TestUpload();
}
// 标准用法
@@ -90,5 +92,41 @@ namespace SDKTest
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
private static void TestUpload()
{
DemoFileUploadRequest request = new DemoFileUploadRequest();
DemoFileUploadModel model = new DemoFileUploadModel
{
Remark = "上传文件参数"
};
request.BizModel = model;
string root = Environment.CurrentDirectory;
Console.WriteLine("当前目录{0}", root);
// 文件上传
// 将当前目录下的两个文件上传到服务器
request.AddFile(new UploadFile("file1", root + "/file1.txt"));
request.AddFile(new UploadFile("file2", root + "/file2.txt"));
DemoFileUploadResponse response = client.Execute(request);
if (response.IsSuccess())
{
List<DemoFileUploadResponse.FileMeta> responseFiles = response.Files;
Console.WriteLine("您上传的文件信息:");
responseFiles.ForEach(file =>
{
Console.WriteLine("上传的文件名:{0},文件大小:{1},文件内容:{2}", file.Filename, file.Size, file.Content);
}
);
}
else
{
Console.WriteLine("错误, code:{0}, msg:{1}, subCode:{2}, subMsg:{3}",
response.Code, response.Msg, response.SubCode, response.SubMsg);
}
}
}
}

View File

@@ -60,6 +60,18 @@ namespace SDKCSharp.Request
this.version = version == null ? SdkConfig.DEFAULT_VERSION : version;
}
/// <summary>
/// 添加上传文件
/// </summary>
/// <param name="file">File.</param>
public void AddFile(UploadFile file)
{
if(this.files == null)
{
this.files = new List<UploadFile>();
}
this.files.Add(file);
}
/// <summary>
/// 创建请求表单

View File

@@ -0,0 +1,13 @@
using System;
using SDKCSharp.Response;
namespace SDKCSharp.Request
{
public class DemoFileUploadRequest : BaseRequest<DemoFileUploadResponse>
{
public override string GetMethod()
{
return "demo.file.upload";
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace SDKCSharp.Response
{
public class DemoFileUploadResponse : BaseResponse
{
[JsonProperty("files")]
private List<FileMeta> files = new List<FileMeta>();
public List<FileMeta> Files { get => files; set => files = value; }
public class FileMeta
{
public FileMeta(String filename, long size, String content)
{
this.Filename = filename;
this.Size = size;
this.Content = content;
}
public FileMeta()
{
}
[JsonProperty("filename")]
public String Filename { get; set; }
[JsonProperty("size")]
public long Size { get; set; }
[JsonProperty("content")]
public String Content { get; set; }
}
}
}

View File

@@ -0,0 +1 @@
file1 content内容1

View File

@@ -0,0 +1 @@
file2 content内容2

View File

@@ -25,7 +25,7 @@ public class OpenClient {
private static final Log log = LogFactory.getLog(OpenClient.class);
private static final OpenConfig DEFAULT_CONFIG = new OpenConfig();
public static final String ERROR_RESPONSE_KEY = "error_response";
private static final String ERROR_RESPONSE_KEY = "error_response";
private String url;
private String appId;

View File

@@ -9,6 +9,7 @@ import com.gitee.sop.sdk.response.BaseResponse;
import com.gitee.sop.sdk.util.ClassUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@@ -71,6 +72,17 @@ public abstract class BaseRequest<T extends BaseResponse> {
return SdkConfig.DEFAULT_VERSION;
}
/**
* 添加上传文件
* @param file
*/
public void addFile(UploadFile file) {
if (this.files == null) {
this.files = new ArrayList<>();
}
this.files.add(file);
}
public RequestForm createRequestForm(OpenConfig openConfig) {
// 公共请求参数
Map<String, String> params = new HashMap<String, String>();

View File

@@ -1 +1 @@
file1 content
file1 content内容1

View File

@@ -1 +1 @@
file2 content...
file2 content内容2

View File

@@ -17,7 +17,6 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -87,12 +86,11 @@ public class SdkTest extends TestCase {
model.setRemark("上传文件参数");
request.setBizModel(model);
List<UploadFile> files = new ArrayList<>();
String root = System.getProperty("user.dir");
System.out.println(root);
files.add(new UploadFile("file1", new File(root + "/src/main/resources/file1.txt")));
files.add(new UploadFile("file2", new File(root + "/src/main/resources/file2.txt")));
request.setFiles(files);
// 这里演示将resources下的两个文件上传到服务器
request.addFile(new UploadFile("file1", new File(root + "/src/main/resources/file1.txt")));
request.addFile(new UploadFile("file2", new File(root + "/src/main/resources/file2.txt")));
DemoFileUploadResponse response = client.execute(request);