使用HttpClient 访问接口
private void getdata() {
string BUKRS = "1000";
string WERKS = "";
DateTime MON = DateTime.Now;
string ZDEPA = "";
string ZREPTYPE = "1";
string url = "http://xxxxxx";
string username = "xxxxx";
string password = "xxxxxxx";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
string[] DAPA = new string[] { "DB01", "DB02" };
foreach (string item in DAPA)
{
ZDEPA = item;
for (int i = 1; i < 20; i++)
{
string ZMON = MON.AddMonths(-i).ToString("yyyyMM");
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("BUKRS", BUKRS);
dictionary.Add("WERKS",WERKS);
dictionary.Add("ZMON",ZMON);
dictionary.Add("ZDEPA", ZDEPA);
dictionary.Add("ZREPTYPE",ZREPTYPE);
string json = JsonConvert.SerializeObject(dictionary);
var content = json;
using (HttpClient httpClient = new HttpClient()) {
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
HttpContent httpContent = new StringContent(content, Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Uri address = new Uri(url);
var response = httpClient.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;
}
}
}
}
使用HttpWebRequest和HttpWebResponse获取数据
private async void SAPRKGBINOFO() {
string BUKRS = "1000";
string WERKS = "";
DateTime MON = DateTime.Now;
string ZDEPA = "";
string ZREPTYPE = "1";
string url = "xxxx";
string username = "xxxx";
string password = "xxxx";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));
string[] DAPA = new string[] { "DB01", "DB02" };
foreach (string item in DAPA)
{
ZDEPA = item;
for (int i = 1; i < 20; i++)
{
string ZMON = MON.AddMonths(-i).ToString("yyyyMM");
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("BUKRS", BUKRS);
dictionary.Add("WERKS",WERKS);
dictionary.Add("ZMON",ZMON);
dictionary.Add("ZDEPA", ZDEPA);
dictionary.Add("ZREPTYPE",ZREPTYPE);
string json = JsonConvert.SerializeObject(dictionary);
var content = json;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/html; charset=utf-8";
request.Headers.Add("Authorization", "Basic " + credentials);
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(content);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8";
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
JObject jo = JObject.Parse(retString);
}
}
}