我的Android后台服务有问题。使用http协议发送数据时,它会显示 ClientProtocolException
我的WebAPI
[AcceptVerbs("GET", "POST")]
[ActionName("InsertLocationDetails")]
public string InsertLocationDetails([FromBody]LocationDetails locDetails )
{
return objLocationService.InsertLocationDetails(locDetails.UserId,locDetails.DateTime.ToString(),
locDetails.Latitude,locDetails.Longitude,locDetails.Status.ToString(),locDetails.Location.ToString());
}
我的LocationDetails类有paramaters
public class LocationDetails
{
public int UserId { get; set; }
public Double Latitude { get; set; }
public Double Longitude { get; set; }
public string Status { get; set; }
public string DateTime { get; set; }
public string Location { get; set; }
}
在我的Android背景代码中我使用http协议。我需要与我的web api服务进行通信以插入数据
public String insertLocationDetails(int userid,String newtime,String status,double latitude,double longitude,String address,String city,String country)
{
HostUrl="http://URL/ServiceName/InsertLocationDetails";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(HostUrl);
try
{
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("UserId",String.valueOf(userid)));
params.add(new BasicNameValuePair("DateTime", newtime));
params.add(new BasicNameValuePair("Latitude",String.valueOf(latitude)));
params.add(new BasicNameValuePair("Longitude",String.valueOf(longitude)));
params.add(new BasicNameValuePair("Status",status));
params.add(new BasicNameValuePair("Location",(address+","+city+","+country)));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(entity);
ResponseHandler<String> handler = new BasicResponseHandler();
result =httpClient.execute(httpPost,handler);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
Log.e(TAG, "ClientProtocolException in callWebService(). " + e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.e(TAG, "IOException in callWebService(). " + e.getMessage());
}
return result;
}}
实际上我的jquery代码正常工作并插入值
我的Javascript代码工作正常
function insertLocationDetails()
{
var url=serverUrl();
var urlpath={
UserId : userid,
DateTime : datetime,
Latitude: latitude,
Longitude : longitude,
Status: status,
Location : address };
$.ajax
({
cache: false,
async: true,
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: url +"InsertLocationDetails",
data: JSON.stringify(urlpath),
success: function (result)
{
var result = eval(result);
for (var property in result)
{
}
}
});
}
请帮我弄清楚Android背景服务中的例外情况 请提供正确的代码以便与我的服务进行沟通
提前致谢 ARUN
答案 0 :(得分:1)
您将请求正文作为application / x-www-form-urlencoded发送,但将内容类型设置为JSON。
而不是使用;
`httpPost.setHeader("Content-Type", "application/json");`
使用;
`httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");`