问题
我正在尝试使用HttpWebRequest创建一个REST API调用到我们内部的Jira服务器。但不知怎的,我不断回到(400)Bad Request错误。我也试过WebClient和……
上面代码中的问题是Jira需要的 的 编码凭证 强> 。如果不对凭据进行编码,Jira服务器将返回400 Bad Request错误,但没有特定信息。
我已经为API请求编写了两个新函数,一个用于编码凭证。
public static string PostJsonRequest(string endpoint, string userid, string password, string json) { // Create string to hold JSON response string jsonResponse = string.Empty; using (var client = new WebClient()) { try { client.Encoding = System.Text.Encoding.UTF8; client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password)); client.Headers.Add("Content-Type: application/json"); client.Headers.Add("Accept", "application/json"); var uri = new Uri(endpoint); var response = client.UploadString(uri, "POST", json); jsonResponse = response; } catch (WebException ex) { // Http Error if (ex.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse wrsp = (HttpWebResponse)ex.Response; var statusCode = (int)wrsp.StatusCode; var msg = wrsp.StatusDescription; throw new HttpException(statusCode, msg); } else { throw new HttpException(500, ex.Message); } } } return jsonResponse; }
private static string GetEncodedCredentials(string userid, string password) { string mergedCredentials = string.Format("{0}:{1}", userid, password); byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials); return Convert.ToBase64String(byteCredentials); }