2013-11-23 31 views
-1

`HttpPost的Java(机器人)到ObjC(IOS)

DefaultHttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(urls[0]); 
    JSONObject holder = new JSONObject(); 
    JSONObject userObj = new JSONObject(); 
    String response = null; 
    JSONObject json = new JSONObject(); 

    try { 
     try { 
      // setup the returned values in case 
      // something goes wrong 
      json.put("success", false); 
      json.put("info", "something wrong."); 
      // add the users's info to the post params 
      userObj.put("email", mEmail); 
      userObj.put("password", mPassword); 
      holder.put("user", userObj); 
      StringEntity se = new StringEntity(holder.toString(), "utf-8"); 
      post.setEntity(se); 

      // setup the request headers 
      post.setHeader("Accept", "application/json"); 
      post.setHeader("Content-Type", "application/json"); 

      ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
      response = client.execute(post, responseHandler); 
      json = new JSONObject(response);` 
....... 

==========

向上,Java代码源。由某人撰写。向下,Objective-C代码源(请求是NSMutableURLRequest的指针),我输入这个代码。

===========

NSMutableDictionary *datas = [[NSMutableDictionary alloc]init]; 

    [datas setValue:@"[email protected]" forKey:@"email"]; 
    [datas setValue:@"zxcvbnmm" forKey:@"password"]; 

    NSString *httpbody = [NSString stringWithFormat:@"user=%@",datas]; 
    NSData *httpbodydata = [httpbody dataUsingEncoding:NSUTF8StringEncoding]; 
    [request setHTTPBody:httpbodydata]; 
    NSString *length = [NSString stringWithFormat:@"%d",[httpbodydata length]]; 
    [request addValue:length forHTTPHeaderField:@"Content-Length"]; 

    [request setHTTPMethod:@"POST"]; 
    [request setValue:[NSString stringWithFormat:@"application/json"] forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:[NSString stringWithFormat:@"application/json"] forHTTPHeaderField:@"Accept"]; 

    // Perform request and get JSON back as a NSData object 
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; 

===========

什么两个代码之间有什么不同?

结果,Java工作正常,但Objc不能发送json对象!

我只是想发送像Java代码。

和,请告诉我什么StringEntity在那个Java代码做。

回答

0

我可以帮助你的iOS的POST方法,如果我是你,我会与AFNetworking尝试,这将是更容易实现的要求,也将是类似的Java解决方案管理JSON消息。我给你一些代码,可以帮助:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
NSDictionary *parameters = @{@"foo": @"bar"}; 
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"JSON: %@", responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Error: %@", error); 
}];