Advertisement
Guest User

Untitled

a guest
May 30th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. /**
  2. * @method prepareRequest
  3. * @param {object} e Callback event
  4. */
  5. var window = Ti.UI.createWindow();
  6. var button1 = Ti.UI.createButton({title:"Basic request", top: 30});
  7. var button2 = Ti.UI.createButton({title:"Auth request", top: 90});
  8. window.add(button1);
  9. window.add(button2);
  10.  
  11. button1.addEventListener('click', prepareRequest);
  12. button2.addEventListener('click', prepareRequest);
  13.  
  14. function prepareRequest(e) {
  15. var withCredentials = true;
  16.  
  17. request(withCredentials);
  18. }
  19.  
  20. /**
  21. * Make a request
  22. * @method request
  23. * @param {boolean} withCredentials Flag for make a auth request or not
  24. */
  25. function request(withCredentials) {
  26. var client,
  27. config,
  28. url,
  29. data;
  30.  
  31. data = {
  32. message: 'This is my message'
  33. };
  34.  
  35. config = {
  36. onload: success,
  37. onerror: error,
  38. timeout: 5000
  39. };
  40.  
  41. if (withCredentials) {
  42. url = 'https://srvasic.upv.es/recursos/error401.asp';
  43. //config.withCredentials = true;
  44. config.username = 'user';
  45. config.password = 'p$wd';
  46. } else {
  47. url = 'https://httpbin.org/post';
  48. }
  49.  
  50. console.log('HTTP CLIENT CONFIG ' + JSON.stringify(config));
  51.  
  52. client = Ti.Network.createHTTPClient(config);
  53. client.setOnload(success);
  54. client.setOnerror(error);
  55.  
  56. try {
  57. console.log('URL: ' + url);
  58. client.open('POST', url);
  59. } catch (e) {
  60. console.log('error opening client');
  61. console.log(JSON.stringify(e));
  62. }
  63.  
  64. try {
  65. client.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  66. } catch (e) {
  67. console.log('error setting request headers');
  68. console.log(JSON.stringify(e));
  69. }
  70.  
  71. try {
  72. client.send(data);
  73. } catch (e) {
  74. console.log('error sending data');
  75. console.log(JSON.stringify(e));
  76. }
  77. }
  78.  
  79. /**
  80. * HttpClient Success Callback
  81. * @method success
  82. * @param {object} e Callback Event
  83. */
  84. function success(e) {
  85. console.log('Success callback: ' + this.responseText);
  86. }
  87.  
  88. /**
  89. * HttpClient Error Callback
  90. * @method error
  91. * @param {object} e Callback Event
  92. */
  93. function error(e) {
  94. console.log('Error callback : ' + e.error);
  95. }
  96.  
  97. window.open();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement