【问题标题】:How to send a data using JSON in Xcode如何在 Xcode 中使用 JSON 发送数据
【发布时间】:2014-05-26 06:44:48
【问题描述】:

我正在为 iOS 编写一个字典应用程序。

我需要从一种语言翻译成另一种语言。

我有 2 个文本视图。在第一个(textView1)中,我必须输入一个要翻译的单词,在第二个(textView)中,当我按下“翻译”按钮时,翻译必须出现。 所以我需要发送

{"SourceText":"%@","CheckCode":"something","TranslateDirection":"0","SubjectBase":"8"},[[self textView1] text].

假设我的 URL API 是:http://fakesite.com/api/fake。我做错了什么?

-(IBAction)translate
{
    NSString *post = [NSString stringWithFormat:@"{\"SourceText\":\"%@\",\"CheckCode\":\something\",\"TranslateDirection\":\"0\",\"SubjectBase\":\"8\"}",[[self textView1] text]];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://fakesite.com/api/fake"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLResponse *response;
    NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSUTF8StringEncoding ];
    _textView.text=theReply;
}

当我按下“翻译按钮”时,第二个 textView 中会出现以下消息:{"Message":"An error has occurred."} 看,我已经在 Android 的 java 中完成了这个,但是由于我是 Xcode 的新手,所以我很困惑如何去做。这是我的 java 文件作为示例。 Mainactivity.java

public class MainActivity extends Activity implements OnClickListener {

public String URL = "http://fakesite.com/api/fake";
EditText text_input;
EditText output;
Button but_tr;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.user_interface);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }


    output = (EditText) findViewById(R.id.text_output);
    but_tr = (Button) findViewById(R.id.button_translate);




    // add click listener to Button "POST"
    but_tr.setOnClickListener(this);

}

 @Override
    public void onClick(View view) {                                    
     String txt = text_input.getText().toString();
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);  
     nameValuePairs.add(new BasicNameValuePair("SourceText", txt));
     nameValuePairs.add(new BasicNameValuePair("CheckCode", "1q2w3e"));
     nameValuePairs.add(new BasicNameValuePair("TranslateDirection", "0"));
     nameValuePairs.add(new BasicNameValuePair("SubjectsBase", "8"));       
     API_Post post = new API_Post(URL, nameValuePairs);
     String Response = post.postData().toString().replace("\\r\\n", "");
     output.setText(Response.substring(51, Response.length() -2).replace("\\n", System.getProperty("line.separator")));         
    }   

}

API_Post.java

public class API_Post {
String url;
List<NameValuePair> nameValuePairs;
public API_Post(String str, List<NameValuePair> params) {
 this.url = str;
  this.nameValuePairs = params;
}
public String postData() {
 HttpClient httpclient = new DefaultHttpClient();  
 HttpPost httppost = new HttpPost(this.url);
StringBuilder builder = new StringBuilder();
try {
httppost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs, HTTP.UTF_8 ));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
      int statusCode = statusLine.getStatusCode();
 Log.d("RestClient", "Status Code : " + statusCode);
 HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
 String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
{
      builder.append(line);
  }
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return builder.toString();
}
}

所以我需要类似的 Xcode 代码。谢谢

【问题讨论】:

  • 可以发原始网址吗?
  • 是的。我可以使用 Postman chrome 客户端检查它

标签: android iphone objective-c json ios7


【解决方案1】:

使用 ASIHTTP 第三方库将节省您的时间。

NSString *post = [NSString stringWithFormat:@"{\"SourceText\":\"%@\",\"CheckCode\":\something\",\"TranslateDirection\":\"0\",\"SubjectBase\":\"8\"}",[[self textView1] text]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://fakesite.com/api/fake"]];
[request setRequestMethod:@"POST"];
[request setResponseEncoding:NSISOLatin1StringEncoding];
[request setPostFormat:ASIMultipartFormDataPostFormat];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

[request setCompletionBlock:^{

    NSDictionary *responseDict = [NSDictionary dictionaryWithXMLData:[request responseData]];

    DLog(@"Response : %@",responseDict);


}];
[request setFailedBlock:^{

}];

[request startAsynchronous];

【讨论】:

    【解决方案2】:

    你可以试试下面的 Obj C 代码:

        NSData *postData = [poststring dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:feedURLString]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120];
    
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    在此之前要检查 Api 是否正确,您可以使用 Google Postman。

    【讨论】:

      【解决方案3】:

      我会推荐你​​,to check this tutorial。这样它在其他项目中也可以重用,并且您的请求中的每个对象都有一个类,这可能更容易处理。因此,您只需在每次再次使用时更改 requests 对象即可。

      【讨论】:

        【解决方案4】:

        我相信问题出在您正在发送的 json 消息上。它只是一个json格式的字符串, 但不是实际的 json 对象。

        按照您在Android代码中使用的相同方式。在android中使用NSDictionary代替namevaluepairs,然后获取json表示如下。

        NSString *jsonRequest = [jsonDict JSONRepresentation];
        

        在此之后进行 URL 编码并设置为 http 正文。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-12
          • 1970-01-01
          • 2019-03-29
          • 2011-05-26
          • 2012-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多