一、httpRequest上传文件到WebService
场景:隆道云上传接口,文件类型Excel。
1—Java调用
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://127.0.0.1:8080/ecg/api");
String secret = "666";
String timestampNum=System.currentTimeMillis()+"";
List<String> paramNames = new ArrayList();
paramNames.add("name");
paramNames.add("appkey");
paramNames.add("version");
paramNames.add("timestamp");
paramNames.add("projectCode");
Collections.sort(paramNames);
Map<String,String> valueMap = new HashMap();
valueMap.put("name", "longdaoyun.ecg.bidding.uploadBusinessFile");
valueMap.put("appkey", "sbwcd");
valueMap.put("version", "1.0");
valueMap.put("timestamp",timestampNum);
valueMap.put("projectCode", "ZB2019091200004");
StringBuilder paramNameValue = new StringBuilder();
for (String paramName : paramNames) {
paramNameValue.append(paramName).append(valueMap.get(paramName));
}
//签名
String source = secret + paramNameValue.toString() + secret;
String signatures = DigestUtils.md5DigestAsHex(source.getBytes()).toUpperCase();
//body字段初始化
FileBody bin = new FileBody(new File("C:/picture.jpg"));
StringBody name = new StringBody("longdaoyun.ecg.bidding.uploadBusinessFile", ContentType.TEXT_PLAIN);
StringBody appkey = new StringBody("sbwcd", ContentType.TEXT_PLAIN);
StringBody version = new StringBody("1.0", ContentType.TEXT_PLAIN);
StringBody timestamp = new StringBody(timestampNum, ContentType.TEXT_PLAIN);
StringBody projectCode = new StringBody("ZB2019091200004", ContentType.TEXT_PLAIN);
StringBody signature = new StringBody(signatures, ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("file", bin)
.addPart("name", name)
.addPart("appkey",appkey)
.addPart("version",version)
.addPart("timestamp",timestamp)
.addPart("projectCode",projectCode)
.addPart("signature",signature)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseEntityStr = EntityUtils.toString(response.getEntity());
System.out.println(responseEntityStr);
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
二—request报文显示
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="file"; filename="G2020102200014.txt"
Content-Type: text/plain
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="name"
longdaoyun.ecg.purchase.uploadProjectFile
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="version" 1.0
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="appkey" ajyl
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="projectCode" G2020102200014
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="timestamp" 1604020026384
------WebKitFormBoundarycbavurKIOh70o0r4
Content-Disposition: form-data; name="signature" 7DDF2BFC723EE3A85FDAF0DA3B9B9C13
------WebKitFormBoundarycbavurKIOh70o0r4--
三—C#代码
request = (HttpWebRequest)WebRequest.Create(this._url);
//CookieContainer cookieContainer = new CookieContainer();
//request.CookieContainer = cookieContainer;
//request.AllowAutoRedirect = true;
//request.MaximumResponseHeadersLength = 1024;
//request.MaximumAutomaticRedirections = 1;
request.Method = "POST";
//把用户传过来的数据转成UTF-8字节流
string boundary = DateTime.Now.Ticks.ToString("X");
request.ContentType = "multipart/form-data;charset=utf-8;boundary=----WebKitFormBoundary"+boundary;
//组装body
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundary" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundary" + boundary + "--\r\n");
//请求头部
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
StringBuilder sbHeader2 = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n","name"));
byte[] sbHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
byte[] sbHeader2Bytes = Encoding.UTF8.GetBytes(sbHeader2.ToString());
FileStream fs = new FileStream(filePath +"\\"+ fileName, FileMode.Open, FileAccess.Read);
byte[] bArr=new byte[fs.Length];
fs.Read(bArr, 0, bArr.Length);
fs.Close();
try
{
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(sbHeaderBytes, 0, sbHeaderBytes.Length);
postStream.Write(bArr, 0, bArr.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(sbHeader2Bytes, 0, sbHeader2Bytes.Length);
byte[] nameByt=Encoding.UTF8.GetBytes(this._param.name);
postStream.Write(nameByt, 0, nameByt.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
byte[] header3 = Encoding.UTF8.GetBytes(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n", "version"));
postStream.Write(header3, 0, header3.Length);
byte[] versionByt = Encoding.UTF8.GetBytes(this._param.version);
postStream.Write(versionByt, 0, versionByt.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
byte[] header4 = Encoding.UTF8.GetBytes(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n", "appkey"));
postStream.Write(header4, 0, header4.Length);
byte[] appkeyByt = Encoding.UTF8.GetBytes(this._param.appkey);
postStream.Write(appkeyByt, 0, appkeyByt.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
byte[] header5 = Encoding.UTF8.GetBytes(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n", "projectCode"));
postStream.Write(header5, 0, header5.Length);
byte[] projectByt = Encoding.UTF8.GetBytes(this._param.projectCode);
postStream.Write(projectByt, 0, projectByt.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
byte[] header6 = Encoding.UTF8.GetBytes(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n", "timestamp"));
postStream.Write(header6, 0, header6.Length);
byte[] timeByt = Encoding.UTF8.GetBytes(this._param.timestamp);
postStream.Write(timeByt, 0, timeByt.Length);
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
byte[] header7 = Encoding.UTF8.GetBytes(string.Format("Content-Disposition:form-data;name=\"{0}\"\r\n\r\n", "signature"));
postStream.Write(header7, 0, header7.Length);
byte[] signByt = Encoding.UTF8.GetBytes(this._param.signature);
postStream.Write(signByt, 0, signByt.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string returnXml = reader.ReadToEnd(); //利用StreamReader就可以从响应内容从头读到尾
reader.Close();
result = JsonConvert.DeserializeObject<CommonAsset.replyResult>(returnXml);
}
catch (WebException ex)
{
this._error = "[ HttpPost_webERR ]" + ex.Message;
}
catch (Exception ex) {
this._error = "[ HttpPost_ERR ]" + ex.Message;
}