我正在使用C#开发一个REST客户端,它执行以下操作:
但是服务器响应了stateid无效。具有讽刺意味的是,当我使用旧的方式(即Microsoft.XMLHTTP来发出请求)时,同样的过程也可以工作,但它不能与HTTP客户端一起使用。我无法在查询字符串中传输状态ID。 这是我使用HTTP客户端的代码:
User user = new User();
user.uid = "username";
String json = JsonConvert.SerializeObject(user);
MessageBox.Show(json);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = client.PostAsync("api?myhotp", new StringContent(json, Encoding.UTF8, "application/json")).Result;
var contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
var obj = JObject.Parse(contents);
string id = (string)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
String jsonotp = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(jsonotp);
client = new HttpClient();
client.BaseAddress = new Uri("http://fqdn");
client.DefaultRequestHeaders.Add("Accept", "application/json");
response = client.PutAsync("api?StateId="+id, new StringContent(json, Encoding.UTF8, "application/json")).Result;
contents = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(contents);
以下是Microsoft.XMLHTTP的代码:
Type xmlType = Type.GetTypeFromProgID("Microsoft.XMLHTTP");
dynamic objXML = Activator.CreateInstance(xmlType);
objXML.Open("POST", "http://fqdn/api?PolicyId=myhotp", false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
//objXML.setOption(2, 13056);
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());
var obj = JObject.Parse(objXML.responseText.ToString());
String id = (String)obj["state"];
MessageBox.Show(id);
Otp otpObj = new Otp();
otpObj.otp = "123456";
json = JsonConvert.SerializeObject(otpObj);
MessageBox.Show(json);
objXML.Open("PUT", "http://fqdn/api?StateId="+id, false);
objXML.setRequestHeader("Content-Type", "application/json");
objXML.setRequestHeader("Accept", "application/json");
objXML.Send(json);
MessageBox.Show(objXML.status.ToString());
MessageBox.Show(objXML.responseText.ToString());