我遇到了这个问题。希望你能帮忙。
我已经在Java中实现了webservices并使用GET方法在iOS中使用了web服务而没有任何问题。但是我无法使POST方法正常工作。
有什么方法可以检查服务器实现是否正确?在浏览器中输入URL不会调用POST方法。在下面的方法中,什么是错误的?
这是我的服务器实施:
@Path("/v1/consumer/")
public class V1_consumer {
@POST
@Path("/updateConsumptionMetric")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateConsumptionMetric(String incomingData) throws Exception {
String returnString = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
DBC dBC = new DBC();
try{
JSONObject partsData = new JSONObject(incomingData);
System.out.println("jsonData: " + partsData.toString());
int http_code = dBC.updateConsumptionMetricForConsumer(partsData.optInt("ConsumerID"), partsData.optInt("ConsumptionMetric"));
if(http_code == 200){
jsonObject.put("HTTP_CODE", "200");
jsonObject.put("MSG", "Items has been entered successfully");
returnString = jsonArray.put(jsonObject).toString();
}else{
return Response.status(500).entity("Unable to process items").build();
}
} catch(Exception e){
e.printStackTrace();
return Response.status(500).entity("Server was not able to process your request").build();
}
return Response.ok(returnString).build();
}
这是我的iOS实现:
-(void)updateConsumptionMetric:(NSNumber*)metricID forConsumer:(NSNumber*)consumerID{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:consumerID, @"ConsumerID", metricID, @"ConsumptionMetric", nil];
NSData * JsonData =[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://profolo.ddns.net:8080/com.profolo.it.cdss.api/api/v1/consumer/updateConsumptionMetric"]]];
[request setHTTPBody:body];
[request setHTTPMethod:@"POST"];
[NSURLConnection sendAsynchronousRequest: request
queue: queue
completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) {
if (error || !data) {
// Handle the error
NSLog(@"Server Error : %@", error);
} else {
// Handle the success
NSLog(@"Server Response :%@",response);
}
}
];
}
答案 0 :(得分:1)
我确定输入浏览器的URL始终发出GET请求,而不是发送给Web服务的POST请求。所以,我建议您使用其他工具发出POST请求(我建议使用Postman)。
还有一件事,你应该改变这行代码
public Response updateConsumptionMetric(String incomingData)
到
public Response updateConsumptionMetric(@RequestBody String incomingData)