我正在使用Xamarin.Android应用程序。我必须使用内容类型为x-www-form-urlencoded的其余API。我无法成功调用Rest API,在此之前,我消耗了许多Web服务,但是我还是第一次使用这种类型的API。我被困在这。 我尝试了两种消耗方式:
public static string makePostEncodedRequest(string url, string jsonparams)
{
string ret = "";
var httpwebrequest = (HttpWebRequest)WebRequest.Create(url);
httpwebrequest.ContentType = "application/x-www-form-urlencoded";
//httpwebrequest.Accept = Config.JsonHeaderAJ;
httpwebrequest.Method = Methods.Post.ToString();
byte[] bytearray = Encoding.UTF8.GetBytes(jsonparams);
using (var streamWriter = new StreamWriter(httpwebrequest.GetRequestStream(), Encoding.ASCII))
{
streamWriter.Write(bytearray);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpwebrequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
ret = streamReader.ReadToEnd();
}
return ret;
}
下一个是:
Dictionary<string, string> requestParams = new Dictionary<string, string ();
requestParams.Add("value=", data1);
requestParams.Add("&value=", data2);
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
HttpResponseMessage response = client.PostAsync(Config.DomainURl + Config.StudentLoginUrl, new FormUrlEncodedContent(requestParams)).Result;
var tokne = response.Content.ReadAsStringAsync().Result;
}
答案 0 :(得分:0)
我已使用以下代码对我的项目中的用户进行身份验证可能会对您有所帮助。
public static async Task<UserData> GetUserAuth(UserAuth userauth)
{
bool asd= CheckNetWorkStatus().Result;
if (asd)
{
var client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri(UrlAdd);// ("http://192.168.101.119:8475/");
var postData = new List<KeyValuePair<string, string>>();
var dto = new UserAuth { grant_type = userauth.grant_type, password = userauth.password, username = userauth.username };
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("grant_type", userauth.grant_type));
nvc.Add(new KeyValuePair<string, string>("password", userauth.password));
nvc.Add(new KeyValuePair<string, string>("username", userauth.username));
var req = new HttpRequestMessage(HttpMethod.Post, UrlAdd + "token") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
string result = await res.Content.ReadAsStringAsync();
var userData = JsonConvert.DeserializeObject<UserData>(result);
userData.ErrorMessage = "true";
return userData;
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Incorrect Password";
return ud;
}
}
else
{
UserData ud = new UserData();
ud.ErrorMessage = "Check Ur Connectivity";
return ud;
}
}