HttpPost在C#中无法正常工作,但在Android中正常工作
我正在对休息服务执行HttpPost以撤消许可证。在Android上,请求完美运行。HttpPost在C#中无法正常工作,但在Android中正常工作
@Override
protected String doInBackground(String... params)
{
String request = serverUrl + "api/Public/RemoveInstall?DeviceID="+deviceId+"&UserID="+m_userID;
try {
if(!isNetworkAvailable())
{
return "no_accesToken";
}
else
{
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setDoOutput(false);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setConnectTimeout(1500);
conn.setUseCaches(false);
conn.connect();
...
}
上面的代码:但这样做在C#中的帖子的时候,我得到的回应
在Android中“没有行动的请求匹配的控制器上找到”完美的作品,但在C#它不会工作:
public async Task<bool> RevokeLicenseAsync(string userId)
{
if (!IsInternetConnected())
{
errorMsg = "No internet connection";
return false;
}
string deviceId = GetDeviceID();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("DeviceID", deviceId));
postData.Add(new KeyValuePair<string, string>("UserID", userId));
//the header arguments "ContentType" and "ContentLength are filled in automatically"
var formContent = new FormUrlEncodedContent(postData);
if (!String.IsNullOrEmpty(token))
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(serverUrl);
using (var response = await httpClient.PostAsync("api/Public/RemoveInstall",formContent))
{
在你的网址,但在第二个发布参数android的请求,你在身体张贴。
如果第一个工作,然后尝试做相同的第二个。
var requestUri = string.Format("api/Public/RemoveInstall?DeviceID={0}&UserID={1}", deviceId, userId);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri);
using (var httpClient = new HttpClient()) {
httpClient.BaseAddress = new Uri(serverUrl);
using (var response = await httpClient.SendAsync(request)) {
//...other code
非常感谢您提供简短而具体的答案 – PrisonMike
什么时候应该将参数放在身体而不是头部?这是因为如果将参数放在主体中,参数将被ssl加密? – PrisonMike
@PrisonMike,这是一个非常广泛的话题。我也确信这个答案已经在网站上。我的回答仅针对最初发布的问题,即您尝试使用两种不同方法访问服务的问题。 – Nkosi
你可以改变如下
public async Task<bool> RevokeLicenseAsync([FromBody]string userId),
,如果你做一个类型参数post请求,你必须指定FromBody或FormUri
当我尝试那样做时出现编译器错误 – PrisonMike
编译器错误的细节是什么? –
第二个具有'=的'的DeviceID在POST,而不是GET –
在您发布的URL的参数机器人请求,但第二个,你将它张贴在体内。如果第一个工作,然后对第二个工作也一样。 – Nkosi
噢好吧我会考虑它感谢 – PrisonMike