在API集成方面需要帮助 [英] need help in API integration
本文介绍了在API集成方面需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
在网络应用程序中,我必须使用api将文件上传到另一个站点/服务器。
请帮助缩短此查询..
$代码下面的b $ b给出了操作有超时错误。
hello,
In web application i have to upload file to another site/server using api.
Please help to shortout this query..
below code gives "Operation has timeout error."
if (FileUpload1.HasFile)
{
string path = Path.GetFullPath(FileUpload1.PostedFile.FileName);
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath(@"~/upload/" + fileName);
string URLAuth = "http://enterprise.smsgupshup.com/GatewayAPI/rest";
FileUpload1.SaveAs(fileLocation);
WebClient wbClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["method"] = "xlsUpload";
formData["userid"] = "xxxxx";
formData["password"] = "xxxxxx";
formData["v"] = "1.1";
formData["filetype"] = "xls";
//formData["msg_type"] = "Text";
formData["auth_scheme"] = "PLAIN";
formData["xlsfile"] = fileLocation;
UploadFilesToRemoteUrl(URLAuth, fileLocation, fileLocation, formData);
}
public static void UploadFilesToRemoteUrl(string url, string files, string logpath, NameValueCollection nvc)
{
try
{
long length = 0;
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
//string boundary = "ou812--------------8c405ee4e38917c";
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
string header = string.Format(headerTemplate, "uplTheFile", files);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
httpWebRequest2.MaximumResponseHeadersLength = 100000;
httpWebRequest2.ReadWriteTimeout = 200000;
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string s = (reader2.ReadToEnd());
stream2.Flush();
stream2.Close();
requestStream.Flush();
requestStream.Close();
reader2.Close();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
}
catch (Exception ex)
{
}
}
}
推荐答案
参考这些链接
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread / 5afef094-ae39-4070-9977-0cb06951cdd4 [ ^ ]
http://geekswithblogs.net/SoftwareDoneRight/archive/2010/09/14/supporting-request-timeout-with- a-webclient.aspx [ ^ ]
Refer these links
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/5afef094-ae39-4070-9977-0cb06951cdd4[^]
http://geekswithblogs.net/SoftwareDoneRight/archive/2010/09/14/supporting-request-timeout-with-a-webclient.aspx[^]
Kinjal,
建议您使用数据驱动的请求系统,而不是直接上传
插入请求数据&运行循环
Kinjal,
You are recommended to use data driven request system, not direct by upload
insert request to data & run loop
httpWebRequest2.MaximumResponseHeadersLength = 100000;
httpWebRequest2.ReadWriteTimeout = 200000;
你得到了你自己的价值
请参考下面给出的bulksms的api样本
祝你好运>
you get set your own value
plz refer below given bulksms''s api sample
Good Luck
//================================================ C# Send Batch code sample ================================================//
/* We use the HttpUtility class from the System.Web namespace
*
* If you see of the error "'HttpUtility' is not declared", you are probably
* using a newer version of Visual Studio. You need to navigate to
* Project | <Project name> Properties | Application,
* and select e.g. ".NET Framework 4" instead of ".NET Framework 4 Client Profile" as your 'Target framework'.
*
* Next, visit Project | Add reference, and select "System.Web" (specifically
* System.Web - not System.Web.<something>).
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
namespace C_Sharp_sendbatch
{
class BatchSMS{
public static string Post(string url, string data){
string result = null;
try{
byte[] buffer = Encoding.Default.GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
Stream PostData = WebReq.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Stream Response = WebResp.GetResponseStream();
StreamReader _Response = new StreamReader(Response);
result = _Response.ReadToEnd();
}
catch (Exception ex){
Console.WriteLine(ex.Message);
}
return result.Trim() + "\n";
}
static void Main(string[] args){
TextReader tr = new StreamReader(@"\Path\to\your\batch_file");
// E.g. TextReader tr = new StreamReader(@"C:\Users\user\Desktop\my_batch_file.csv")
// Please see http://bulksms.vsms.net/docs/eapi/submission/send_batch/ for information
// on what the format of your input file should be.
string line;
string batch = "";
while ((line = tr.ReadLine()) != null){
batch += line + "\n";
}
//Console.WriteLine(batch);
tr.Close();
string url = "http://bulksms.vsms.net:5567/eapi/submission/send_batch/1/1.0";
/*****************************************************************************************************
**Construct data
*****************************************************************************************************/
/*
* Note the suggested encoding for the some parameters, notably
* the username, password and especially the message. ISO-8859-1
* is essentially the character set that we use for message bodies,
* with a few exceptions for e.g. Greek characters. For a full list,
* see: http://bulksms.vsms.net/docs/eapi/submission/character_encoding/
*/
string data = "";
data += "username=" + HttpUtility.UrlEncode("your_username", System.Text.Encoding.GetEncoding("ISO-8859-1"));
data += "&password=" + HttpUtility.UrlEncode("your_password", System.Text.Encoding.GetEncoding("ISO-8859-1"));
data += "&batch_data=" + HttpUtility.UrlEncode(batch, System.Text.Encoding.GetEncoding("ISO-8859-1"));
data += "&want_report=1";
string sms_result = Post(url, data);
string[] parts = sms_result.Split('|');
string statusCode = parts[0];
string statusString = parts[1];
if (!statusCode.Equals("0")){
Console.WriteLine("Error: " + statusCode + ": " + statusString);
}
else{
Console.WriteLine("Success: batch ID " + parts[2]);
}
Console.ReadLine();
}
}
}
这篇关于在API集成方面需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文