如何在Xcode中使用JSON发送数据

时间:2014-05-26 06:44:49

标签: android iphone objective-c json ios7

我正在为iOS编写一本词典应用程序。

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

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

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

假设我的网址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."} 看看我已经在java for Android中完成了这个,但由于我是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代码。感谢

4 个答案:

答案 0 :(得分:0)

使用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];

答案 1 :(得分:0)

您可以尝试使用以下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。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

NSString *jsonRequest = [jsonDict JSONRepresentation];

此后执行URL编码并设置为http body。