我命由我不由天

机会是干出来的!

.net 对接极兔平台 java Base64与.net Base64数据不一致及POST 带header 和body 参数的处理

近几天对接极兔平台,遇到java Base64与.net Base64数据不一致及POST 带header 和body 参数的问题,费了一些周折,现在记录下来,供大家参考。

1. java Base64与.net Base64数据不一致。

 

 

在网上找了很多,都不对症,直到看到这篇:https://blog.csdn.net/weixin_42358173/article/details/114072001

原来如此简单:Convert.ToBase64String(字节数组.)即可

public static string JavaMD5ToBase64String(string input)
{
//Java,将数据直接放入字节数组,.NET中,不要使用String,使用字节数组.
var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
var md5Byte = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
return Convert.ToBase64String(md5Byte);
}

2.POST 带header 和body 

 

 

网上找了不少资料,都不对症,但给了启发,直接上码:

public static string DoPost(string url, IDictionary<string, string> bodyParameters, IDictionary<string, string> headerParameters = null)
{
try
{
HttpWebRequest req = GetWebRequest(url, "POST");
req.ContentType = "application/x-www-form-urlencoded";
if (headerParameters != null)
{
IEnumerator<KeyValuePair<string, string>> dem = headerParameters.GetEnumerator();
while (dem.MoveNext())
{
req.Headers.Add(dem.Current.Key, dem.Current.Value);
}
}
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(bodyParameters));
Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();

HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding("utf-8");
var result = GetResponseAsString(rsp, encoding);
return result;
}
catch (Exception e)
{
throw e;
}
}

 

public static string BuildQuery(IDictionary<string, string> parameters)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;

IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
StringBuilder builder = new StringBuilder();
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
hasParam = true;
}
}

return postData.ToString();
}

 

方法调用:

var headerParameters = new Dictionary<string, string>
{
{"apiAccount", apiAccount} , 
{"digest", digest},
{"timestamp",timestamp}
};

var bodyParameters = new Dictionary<string, string>
{
{"bizContent", responseJson }
};

 

  var result = DoPost(r, bodyParameters, headerParameters);

 

posted on 2023-01-31 20:03  Kylinhe  阅读(212)  评论(0编辑  收藏  举报

导航