草庐IT

iPhone XML请求

coder 2024-06-28 原文

我有一个 API 可以向服务器发送 XML 请求:

<?xml version="1.0" encoding="UTF-8"?>
<request type="handle" action="update">
<userdata>
<username>YourUsername</username>
<password>YourPassword</password>
</userdata>
<handledata type="PERSON" id="HandleId">
<name>Mustermann</name>
<firstname>Max</firstname>
<organization>Firma KG</organization>
<street>Musterstrasse 1</street>
<postalcode>11111</postalcode>
<city>Musterstadt</city>
<state>Niedersachsen</state>
<country>DE</country>
<email>email@adresse.de</email>
<phone>+43-111-111111</phone>
<fax>+43-111-111111</fax>
<remarks>remarks</remarks>
</handledata>
</request>

如何在 iPhone 上执行此操作?

最佳答案

您可以使用libxml2。我怀疑这是最快的方法。将其框架添加到您的项目中(请参阅 this document 的“设置您的项目”部分)。

在您的 XML 编写器的 header 中,添加以下导入:

#import <libxml/encoding.h>
#import <libxml/xmlwriter.h>

在实现中,编写一个方法来生成您的 XML。假设您将通过 NSData* 对象发送请求的字节,因此您可能会这样写:

- (NSData *) xmlDataFromRequest 
{
    xmlTextWriterPtr _writer;
    xmlBufferPtr _buf;
    xmlChar *_tmp;
    const char *_UTF8Encoding = "UTF-8";

    _buf = xmlBufferCreate();
    _writer = xmlNewTextWriterMemory(_buf, 0);

    // <?xml version="1.0" encoding="UTF-8"?>
    xmlTextWriterStartDocument(_writer, "1.0", _UTF8Encoding, NULL);

    // <request type="handle" action="update">
    xmlTextWriterStartElement(_writer, BAD_CAST "request");
    xmlTextWriterWriteAttribute(_writer, BAD_CAST "type", BAD_CAST "handle");
    xmlTextWriterWriteAttribute(_writer, BAD_CAST "action", BAD_CAST "update");
    xmlTextWriterEndElement(_writer);

    // <userdata>...</userdata>
    xmlTextWriterStartElement(_writer, BAD_CAST "userdata");
    xmlTextWriterStartElement(_writer, BAD_CAST "username");
    _tmp = [self xmlCharPtrForInput:[[NSString stringWithFormat:@"YourUsername"] cStringUsingEncoding:NSUTF8StringEncoding] withEncoding:_UTF8Encoding];
    xmlTextWriterWriteString(_writer, _tmp);
    xmlTextWriterEndElement(_writer); // closing <username>
    xmlFree(_tmp);
    xmlTextWriterStartElement(_writer, BAD_CAST "password");
    _tmp = [self xmlCharPtrForInput:[[NSString stringWithFormat:@"YourPassword"] cStringUsingEncoding:NSUTF8StringEncoding] withEncoding:_UTF8Encoding];
    xmlTextWriterWriteString(_writer, _tmp);
    xmlTextWriterEndElement(_writer); // closing <password>
    xmlFree(_tmp); 
    xmlTextWriterEndElement(_writer); // closing <userdata>

    // etc.

    xmlTextWriterEndDocument(_writer);
    xmlFreeTextWriter(_writer);

    // turn libxml2 buffer into NSData* object

    NSData *_xmlData = [NSData dataWithBytes:(_buf->content) length:(_buf->use)];
    xmlBufferFree(_buf);

    return _xmlData;
}

我这里有一个辅助方法,用于将 const char * 转换为 xmlChar *:

- (xmlChar *) xmlCharPtrForInput:(const char *)_input withEncoding:(const char *)_encoding 
{
    xmlChar *_output;
    int _ret;
    int _size;
    int _outputSize;
    int _temp;
    xmlCharEncodingHandlerPtr _handler;

    if (_input == 0)
        return 0;

    _handler = xmlFindCharEncodingHandler(_encoding);

    if (!_handler) {
        NSLog(@"convertInput: no encoding handler found for '%s'\n", (_encoding ? _encoding : ""));
        return 0;
    }

    _size = (int) strlen(_input) + 1;
    _outputSize = _size * 2 - 1;
    _output = (unsigned char *) xmlMalloc((size_t) _outputSize);

    if (_output != 0) {
        _temp = _size - 1;
        _ret = _handler->input(_output, &_outputSize, (const xmlChar *) _input, &_temp);
        if ((_ret < 0) || (_temp - _size + 1)) {
            if (_ret < 0) {
                NSLog(@"convertInput: conversion wasn't successful.\n");
            } else {
                NSLog(@"convertInput: conversion wasn't successful. Converted: %i octets.\n", _temp);
            }   
            xmlFree(_output);
            _output = 0;
        } else {
            _output = (unsigned char *) xmlRealloc(_output, _outputSize + 1);
            _output[_outputSize] = 0;  /*null terminating out */
        }
    } else {
        NSLog(@"convertInput: no memory\n");
    }

    return _output;
}

关于iPhone XML请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1822131/

有关iPhone XML请求的更多相关文章

  1. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  2. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  3. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

  4. ruby-on-rails - 获取并发布相同匹配项的请求 - 2

    在我的路线文件中我有:match'graphs/(:id(/:action))'=>'graphs#(:action)'如果是GET请求(工作)或POST请求(不工作),我想匹配它我知道我可以使用以下方法在资源中声明POST请求:post'/'=>:show,:on=>:member但是我怎样才能为比赛做到这一点呢?谢谢。 最佳答案 如果你同时想要POST和GETmatch'graphs/(:id(/:action))'=>'graphs#(:action)',:via=>[:get,:post]编辑默认值可以设置如下match'g

  5. ruby-on-rails - 如何在 ActionController::TestCase 请求中设置内容类型 - 2

    我试图像这样在我的测试用例中执行获取:request.env['CONTENT_TYPE']='application/json'get:index,:application_name=>"Heka"虽然,它失败了:ActionView::MissingTemplate:Missingtemplatealarm_events/indexwith{:handlers=>[:builder,:haml,:erb,:rjs,:rhtml,:rxml],:locale=>[:en,:en],:formats=>[:html]尽管在我的Controller中我有:respond_to:html,

  6. ruby - 如何测试 (rspec) 花费太长时间的 http 请求? - 2

    如果使用rspec请求花费的时间太长,我该如何测试行为?我正在考虑使用线程来模拟这个:describe"Test"doit"shouldtimeoutiftherequesttakestoolong"dolambda{thread1=Thread.new{#net::httprequesttogoogle.com}thread2=Thread.new{sleep(xxseconds)}thread1.jointhread2.join}.shouldraise_errorendend我想确保在第一次发出请求后,另一个线程“启动”,在这种情况下只是休眠xx秒。然后我应该期望请求超时,因为执

  7. ruby - Sinatra 路由中定义的全局变量是否在请求之间共享? - 2

    假设我有:get'/'do$random=Random.rand()response.body=$randomend如果我每秒有数千个请求到达/,$random是否会被共享并“泄漏”到上下文之外,或者它会像getblock的“本地”变量一样?我想如果它是在get'/'do的上下文之外定义的,它确实会被共享,但我想知道在ruby​​中是否有我不知道的$机制。 最佳答案 ThispartoftheSinatraREADMEaboutscopeisalwayshelpfultoread但是,如果您只需要为请求保留变量,那么我认为我建议使用

  8. ruby - 无法安装 ruby​​ 1.9.3 获取请求的 URL 不存在 - 2

    运行以下命令时:rvminstall1.9.3我得到以下输出:Error:therequestedURLdoesnotexist:ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-.tar.bz2我已将rvm更新到最新版本并输入rvmreload有什么想法吗? 最佳答案 URL应该是这样的:ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p194.tar.bz2尝试更新您的rvmrvmgethead然后安装1.9.3rvminstall1.9.3

  9. ruby-on-rails - 如何通过 HTTParty 通过 PUT 请求发送空数组? - 2

    我有一个具有“名称”属性和“标签”属性的照片类。我的目标是在Rails中实现一个更新功能,用输入的内容替换照片的标签。例如,如果我尝试PUT一个将“标签”设置为[]的JSON对象,我希望从照片中清除任何标签。但是,当我通过HTTParty提交一个空数组作为主体参数之一时,我相信HTTParty正在将[]翻译成nil。因此,我的Rails后端的photos#update端点没有接收到任何参数“tags”。我正在寻找一种方法让HTTParty不将[]转换为nil,因为我失去了从照片中删除标签的能力。 最佳答案 这是Rails4中的一个错

  10. ruby - 为什么我必须对 Net::HTTP 请求的安全字符进行 URI.encode? - 2

    我尝试使用Net::HTTP向Twitter发送GET请求(出于隐私原因替换了用户ID):url=URI.parse("http://api.twitter.com/1/friends/ids.json?user_id=12345")resp=Net::HTTP.get_response(url)这会在Net::HTTP中引发异常:NoMethodError:undefinedmethodempty?'for#from/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:1

随机推荐