<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>HTTPSocket &#8211; Xojo Programming Blog</title>
	<atom:link href="https://blog.xojo.com/tag/httpsocket/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.xojo.com</link>
	<description>Blog about the Xojo programming language and IDE</description>
	<lastBuildDate>Mon, 12 Jun 2023 11:44:56 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Web Services Part II: Xojo Web, at your service</title>
		<link>https://blog.xojo.com/2018/11/08/web-services-part-ii-xojo-web-at-your-service/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Thu, 08 Nov 2018 10:00:10 +0000</pubDate>
				<category><![CDATA[Cross-Platform]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<category><![CDATA[Middleware]]></category>
		<category><![CDATA[Web Service]]></category>
		<category><![CDATA[webdev]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=5118</guid>

					<description><![CDATA[In a previous entry we started to dig into web services with Xojo. The first post focused on the backend (server side), creating the Xojo&#8230;]]></description>
										<content:encoded><![CDATA[<p>In a <a href="https://blog.xojo.com/2018/09/26/web-services-xojo-web-at-your-service/">previous entry</a> we started to dig into web services with Xojo. The first post focused on the backend (server side), creating the Xojo app acting as middleware between the clients and the database that holds your data. We are using SQLite as the backend engine but it would not be difficult to change to other supported database engines like PostgreSQL, MySQL (MariaDB), Oracle or SQL Server, and even ODBC; all of these are supported by Xojo!<span id="more-5118"></span></p>
<p>In this second post on the topic we will focus on the client side desktop app that will be in charge of creating the requests using the web service published API. This desktop app will send new data to our web server app so it can be added to the backend database.</p>
<p>The main topics are:</p>
<ul>
<li>Creating a subclass from the <code>URLConnection</code> class</li>
<li>Dealing with the data received from the server as result for the request</li>
<li>Encoding a <code>JSONItem</code> for sending data to the web service</li>
</ul>
<p>As stated in the previous entry, the example doesn&#8217;t include the normal (and recommended) verifications on the data provided and received or the check on possible errors; we are only focused on the main topic.</p>
<h2>Creating an URLConnection subclass</h2>
<p>Let&#8217;s start by creating a new desktop project. Add a new Class using <code>Insert &gt; Class</code> and use the Inspector to assign <code>URLConnection</code> as the <b>Super Data Type</b> as shown in the picture:</p>
<p><img fetchpriority="high" decoding="async" class="size-full wp-image-11609 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass.png" alt="" width="602" height="300" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass.png 602w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnectionSubclass-300x150.png 300w" sizes="(max-width: 602px) 100vw, 602px" /></p>
<p>With the just added class still selected in the Navigator (the leftmost column in the IDE Window), add a new property to it (<code>Insert &gt; Property</code>). We will use this property so it points to a DesktopListBox in our user interface, and so we can update it with the data received from our web service. With the just added property still selected, use the Inspector to set its Data Type and Name (text label used from our code to refer to such property) as follows:</p>
<ul>
<li><b>Name</b>: List</li>
<li><b>Type</b>: DesktopListBox</li>
<li><b>Scope</b>: Private</li>
</ul>
<p>Note that we set the scope as <b>Private</b>. This means that this property can be accessed only from the instances of the class, and not those that are created from other data types or even those created as subclasses from this class.</p>
<h2>URLConnection: Asynchronous communications</h2>
<p>Why would we want to maintain a reference to a ListBox control in our URLConnection class? As with any kind of problem, we can take several approaches in order to solve it. In this case, is a very convenient way to get a reference to the control we want to update as we will be using the URLConnection asynchronously.</p>
<p>Once we call the request against our web service, the execution of the app will not be paused until we receive a response, this allows the user to do other operations if they want. In this case the class instance, via the <code>ContentReceived</code> event, will be responsible to receive the new data from the web service, so we can use it.</p>
<p>In fact, this is our next step. With our <code>URLConnection</code> subclass still selected in the Navigator, add a new Event Handler to it (<code>Insert &gt; Event Handler…</code>). In the resulting window, choose the <code>PageReceived</code> option from the list and confirm the selection, so the event will be added to the class under the <b>Event Handlers</b> section.</p>
<p><img decoding="async" class="size-large wp-image-11610 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-1024x563.png" alt="" width="1024" height="563" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-1024x563.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-300x165.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived-768x423.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/URLConnection-ContentReceived.png 1236w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>Now, with the just added Event Handler still selected, write the following snippet of code in the associated Code Editor:</p>
<pre>#Pragma Unused url

If HTTPStatus = 200 Then // We received an OK as the status for our request
  If Content.Length &lt;&gt; 0 Then // And we have data to process as part of the reply
    List.RemoveAllRows // So we delete previous existing entries in the associated ListBox Control
    content = content.DefineEncoding(Encodings.UTF8) // We set the encoding for the received data
    
    Var items As Dictionary = ParseJSON(content) // And proceed to create a new dictionary from the received data in JSON format
    items = items.Value("AllAlbums") // We get all the items for the key 'AllAlbums'…
    For Each item As DictionaryEntry In items // …iterating on them…
      Dim tempDict As Dictionary = item.Value // …and retrieving the dictionary (JSON item) for it…
      Dim title As String = tempDict.Value("title") // …so we finally access the desired value
      list.AddRow title
    Next
  End If
End If</pre>
<p>The code is commented so you can follow what happens in each line in the process; but it is worth it to point out that the <code>ContentReceived</code> event gives us all the parameters we need in order to work with the data sent from the web service:</p>
<ul>
<li><b>URL</b>: The URL returned as the reply for our request</li>
<li><b>HTTPStatus</b>: The HTTP status code that you <b>should</b> read to verify the success of the request</li>
<li><b>Content</b>: This is a String that can contain the data associated with the reply.</li>
</ul>
<p>In addition, you can also add an extra event handler to our subclass: <code>Error</code>. This will be fired when an error is produced while dealing with requests sent from the instance.</p>
<p>With the events and property already set, it is time to add a couple of methods in charge of commanding our URLConnection subclass to launch the requests. For our example, those method names are directly related to the operations we want to do on the web service API created on the first part of this tutorial.</p>
<p>So, with our URLConnection class still selected in the Navigator, add a new method (<code>Insert &gt; Method</code>), using the following data in the associated Inspector. This is the method in charge of requesting our web service for the name of all the available albums. Of course, we expect to receive the reply through the <code>ContentReceived</code> event:</p>
<ul>
<li><b>Method Name</b>: GetRequest</li>
<li><b>Parameters</b>: theList As DesktopListBox, theURL as String</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>As you can see, this method expects to receive the reference to a <b>DesktopoListBox</b> control, and the text to the URL that should be the end point of our web service. Now put the following code in the associated Code Editor for the just added Method:</p>
<pre>List = theList
self.send("GET", theURL)</pre>
<p>Simple, isn&#8217;t? As you can see, we save the reference to the DesktopListBox control in the instance property so we can use it later for updating its contents with the received data. Then we use the <code>Send</code> method from the class with the <code>GET</code> verb and the URL where our web service should be listening for incoming requests. As previously stated, this is an async operation, so we will let our object to react through the <code>ContentReceived</code> or <code>Error</code> events.</p>
<h2>URLConnection: Sending data as part of a request</h2>
<p>Add a new method to the subclass, using the following values in the resulting Inspector. This is the method allowing us to send data to the web service so they can be added to the backend database:</p>
<ul>
<li><b>Method Name</b>: SendItem</li>
<li><b>Parameters</b>: Item As JSONItem, theURL As String</li>
<li><b>Scope</b>: Public</li>
</ul>
<p>This time, the method expects to receive and JSONItem object (pointed via the variable <code>Item)</code> and a String instance that should be the web service endpoint URL. Put the following code in the associated Code Editor for the method:</p>
<pre>Self.SetRequestContent( item.ToString, "application/json" )
self.Send("POST", theURL)</pre>
<p>The URLConnection instances allow us to associate additional information (data) for a request sending, in addition to those added through the HTTP headers (<code>Head</code>), using for that the <code>SetRequestContent</code> method. This method expects two parameters: a String with the real data to attach, and the definition of the type of data we are sending (this is, the <b>MIME</b> Type) as a String instance.</p>
<p>Finally, we launch the request in the second line of code, using for that the URL assigned to the <code>theURL</code> parameter and using the verb <code>POST</code>.</p>
<h2>Designing the User Interface</h2>
<p>We have already finished all the logic behind our example app, via our URLConnection subclass. So now it&#8217;s time to design a minimal user interface so we can verify the correct functionality of our client agains the web service.</p>
<p>Select the <code>Window1</code> object and add the required control so it looks like the one displayed here (from top to bottom): a DesktopListBox, a couple of DesktopTextFields in addition of two DesktopLabels, and two DesktopPushButtons named &#8220;Request&#8221; and &#8220;Send&#8221;.</p>
<p><img decoding="async" class="size-large wp-image-11611 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-1024x744.png" alt="" width="1024" height="744" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-1024x744.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-300x218.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest-768x558.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/DesktopWebServiceTest.png 1382w" sizes="(max-width: 1024px) 100vw, 1024px" /></p>
<p>Next, add an instance of the created URLConnection subclass. For that, simply drag the created subclass from the Project Browser to the Window Layout Editor and a new instance will be added to the Tray in the lower section of the Editor, as shown in the following picture:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-11612 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection.png" alt="" width="596" height="272" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection.png 596w, https://blog.xojo.com/wp-content/uploads/2018/11/MyConnection-300x137.png 300w" sizes="auto, (max-width: 596px) 100vw, 596px" /></p>
<p>The only code present in the user interface is the one that we will add to both PushButtons. Double click the one labeled &#8220;Request&#8221;, and add the following line of code to its <code>Pressed</code> Event Handler:</p>
<p><code>MyConnection1.getRequest(AlbumListbox, "http://127.0.0.1:8081/GetAll")</code></p>
<p>It calls the <code>getRequest</code> method on the instance based on our subclass, sending as parameters the control &#8220;ListBox1&#8221; and the text for the (local) URL where the web service should be listening.</p>
<p>Double click the PushButton labeled &#8220;Send&#8221; in order to add the <code>Pressed</code> Event Handler and write the following fragment of code into the associated Code Editor:</p>
<pre>Var d As New Dictionary
d.Value("Title") = TitleField.Text
d.value("ArtistId") = ArtistIDField.Text
Var item As New JSONItem
item.Value("newAlbum") = d

MyConnection1.sendItem(item,"http://127.0.0.1:8081/AddAlbum")</pre>
<p>As you can see, there is nothing magic in it. We simply create a new dictionary using the keys expected from our web server to access the underlaying data for the record. In addition, you can see how easy it is to create a new JSONItem from a Dictionary!</p>
<p>Then, we simply call the <code>sendItem</code> method on our URLConnection subclass instance, passing along the expected parameters: a JSONItem instance and the web service endpoint URL that should include the method we want to call in the remote API.</p>
<h2>Ready to listen for your requests!</h2>
<p>We have finished our client app! Launch the web service created in the first part of the tutorial (make sure it is listening using the port 8081). Then, run the desktop client app and push the buttons for &#8220;sending&#8221; or &#8220;requesting&#8221; the information. You will see how with the request you&#8217;ll receive all the albums available in the example database, while with the &#8220;Send&#8221; button you&#8217;ll be able to add new records to the database with the data provided in both TextFields.</p>
<p><img loading="lazy" decoding="async" class="size-large wp-image-11613 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-1024x777.png" alt="" width="1024" height="777" srcset="https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-1024x777.png 1024w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-300x228.png 300w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning-768x582.png 768w, https://blog.xojo.com/wp-content/uploads/2018/11/AppRunning.png 1424w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></p>
<p>In conclusion, Xojo allows us to create both the backend and the multiplatform clients in record time and in a really easy way! Obviously, the examples used in these two articles are not, by far, complete solutions you can use &#8220;As Is&#8221;, but they give the basics you can use to construct more robust and complete solutions for your own needs.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages <a href="http://www.aprendexojo.com">AprendeXojo.com</a> and is the developer behind the GuancheMOS plug-in for Xojo Developers, Markdown Parser for Xojo, HTMLColorizer for Xojo and the Snippery app, among others</em></p>
<p>*<a href="https://www.aprendexojo.com/2016/06/crear-servicio-web-con-xojo-parte-ii/">Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>#JustCode Challenge Week 3 &#8211; Dogs Up!</title>
		<link>https://blog.xojo.com/2018/07/06/just-code-challenge-week3/</link>
		
		<dc:creator><![CDATA[Paul Lefebvre]]></dc:creator>
		<pubDate>Fri, 06 Jul 2018 10:00:23 +0000</pubDate>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Fun]]></category>
		<category><![CDATA[#JustCode]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Challenge]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<guid isPermaLink="false">https://blog.xojo.com/?p=4373</guid>

					<description><![CDATA[After 2 desktop apps in week 1 and week 2 of the Just Code challenge, my project this week is an iOS app. It's very important job is to display dog pictures. I call it Dogs Up!]]></description>
										<content:encoded><![CDATA[<p><span style="font-size: 16px;">After 2 desktop apps in week 1 and week 2 of the <a href="https://blog.xojo.com/2018/06/18/jump-right-in-just-code-challenge/">Just Code challenge</a>, my project this week is an iOS app. Its very important job is to display dog pictures. I call it Dogs Up!</span></p>
<p><span id="more-4373"></span></p>
<p>If you were at XDC 2018 maybe you caught my iOS session where I showed how to send an update to the App Store. The app I updated was <a href="https://blog.xojo.com/2015/10/01/cats-up-using-httpsocket-with-the-cat-rest-api/">Cats Up!</a>, a simple iOS app that display cat pictures. Dogs Up! is the dog version and it uses the <a href="https://dog.ceo/dog-api/">Dog API</a>.</p>
<p><img loading="lazy" decoding="async" class="wp-image-4374 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2018/06/iOS55Screenshot.png" alt="" width="281" height="500" /></p>
<p>To make this app, I made a copy of the Cats Up! project and then started changing the parts necessary to hook it up to the Dog API. Changing existing projects is a great way to learn and one of the reasons we are doing the Just Code Challenge.</p>
<p>The Cats Up! project used a single HTTPSocket to connect to its web service for the cat pictures. The Dog API required two HTTPSockets: one to request a URL to a dog picture and another to download the picture itself.</p>
<p>Once these steps were done, I just needed to update the JSON file with dog facts (instead of cat facts), find something to use for the dog icon and get a recording of a dog bark to use when a new picture is displayed.</p>
<p><a href="http://files.xojo.com/JustCode/DogsUp.zip">Download the Dogs Up! project</a>.</p>
<p>Download and check out earlier projects:</p>
<ul>
<li>Week 2: <a href="https://blog.xojo.com/2018/06/29/just-code-challenge-week2/">Password Generator</a></li>
<li>Week 1: <a href="https://blog.xojo.com/2018/06/22/just-code-challenge-week1/">Color Picker</a></li>
</ul>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Xojo.Net.HTTPSocket Speed on Windows</title>
		<link>https://blog.xojo.com/2017/03/09/xojo-net-httpsocket-speed-on-windows/</link>
		
		<dc:creator><![CDATA[Greg O'Lone]]></dc:creator>
		<pubDate>Thu, 09 Mar 2017 06:46:11 +0000</pubDate>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[DNS]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<category><![CDATA[IPv6]]></category>
		<category><![CDATA[Xojo Framework]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=2233</guid>

					<description><![CDATA[There&#8217;s been a bit of discussion about how the new Xojo.Net.HTTPSocket is slow for some users on Windows, which we&#8217;ve been trying to isolate to&#8230;]]></description>
										<content:encoded><![CDATA[<p>There&#8217;s been a bit of discussion about how the new <a href="http://developer.xojo.com/xojo-net-httpsocket">Xojo.Net.HTTPSocket</a> is slow for some users on Windows, which we&#8217;ve been trying to isolate to get fixed.</p>
<p>After a bit of experimentation this January we were able to isolate one huge cause of this annoying behavior. Unfortunately it has to do with a misconfigured IPv6 DNS server configuration and whether or not yours is correct may be up to your service provider.</p>
<h3>Whose bug is this?</h3>
<p>According to the spec, IPv6 DNS servers are <em>supposed to</em> return immediately if they can&#8217;t fulfill the request. Unfortunately this is almost the exact opposite of what an IPv4 DNS server does, in that it <em>may</em> forward your request to the next server to see if it knows where your request should go. Unfortunately we found that only about two-thirds of the ones we tested were correctly configured.</p>
<p>On macOS and Linux, DNS requests are sent concurrently, that is, two requests are sent at the same time, one each for IPv4 and IPv6. The one that returns first is used. On Windows, the requests are unfortunately sent sequentially, IPv6 <em>and then IPv4</em>. What this means is that IPv6 requests just hang there, waiting for a response that will either never come or will wait until the underlying socket reaches its timeout. When that fails, the IPv4 request is sent and fulfilled and your socket request goes through.</p>
<h3>What To Do</h3>
<p>Here are a few things you can do to test this theory. While you can&#8217;t really ask all of your users to do this, it will tell you if this is where the problem lies.</p>
<ol>
<li>Turn off IPv6.
<ol>
<li>Click <strong>Start</strong> and then <strong>Settings.</strong></li>
<li>Search for <strong>Network Connections</strong>.</li>
<li>Click <strong>View network connections</strong>.</li>
<li>Right-click on the active connection and select <strong>Properties</strong>.</li>
<li>On the <strong>Networking</strong> tab, clear the <strong>Internet Protocol Version 6 (TCP/IPv6)</strong> check box, and then click <strong>OK</strong>.</li>
</ol>
</li>
<li>Change the DNS entries for IPv6 from the defaults to point to <a href="https://developers.google.com/speed/public-dns/">Google Public DNS</a> or <a href="http://opendns.com">OpenDNS</a>.</li>
<li>Make a Hosts file entry. If your installer runs as an administrator, you can make an entry in the hosts file to force the computer to use IPv4. <em><em><em>This is not a long term solution as the world moves to IPv6.</em></em></em>The hosts file on Windows 7/8/10 is located at:
<pre>C:\Windows\System32\drivers\etc</pre>
<p>and you should add an entry which looks like this:</p>
<pre>Server IP Address&lt;TAB&gt;domain name</pre>
</li>
<li>If it&#8217;s a domain that you control, make sure you only use IPv4 DNS entries and that your server is only listening on the IPv4 interface.</li>
</ol>
<p>All in all, it&#8217;s a frustrating problem. While there&#8217;s no easy solution, the good news is that because there are no IPv4 addresses left to be distributed, the world <em>is</em> moving to IPv6. The more demand there is, the more likely that the incorrect DNS servers will get fixed because they&#8217;ll cause problems for other sites as well.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>iOS Tutorial: Shorten that URL!</title>
		<link>https://blog.xojo.com/2016/09/20/ios-tutorial-shorten-that-url/</link>
		
		<dc:creator><![CDATA[Javier Menendez]]></dc:creator>
		<pubDate>Tue, 20 Sep 2016 18:51:12 +0000</pubDate>
				<category><![CDATA[iOS]]></category>
		<category><![CDATA[Learning]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Declares]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[Xojo Programming Language]]></category>
		<guid isPermaLink="false">http://blog.xojo.com/?p=1849</guid>

					<description><![CDATA[Make an iOS App that shortens an entered URL using the public API of Bit.ly using a subclass inherited from Xojo.Net.HTTPSocket, and the Declare statement in order to use some functions and methods found on the native Cocoa Touch API.]]></description>
										<content:encoded><![CDATA[<p>In this Xojo tutorial we will see how simple it is to make an <strong>iOS</strong> App that shortens an entered URL using the public API of <a href="https://dev.bitly.com"><strong>Bit.ly</strong></a>. We will use our own subclass inherited from <a href="http://developer.xojo.com/xojo-net-httpsocket" target="_blank" rel="noopener"><strong>Xojo.Net.HTTPSocket</strong></a>, and the Declare statement in order to use some functions and methods found on the native <strong>Cocoa Touch</strong> API. In fact, the use of Declare is mandatory because with the new Xojo Framewok we don&#8217;t yet have access to the <a href="http://developer.xojo.com/encodeurlcomponent" target="_blank" rel="noopener"><strong>EncodeURLComponent</strong></a> function available with the old framework. This one is a big help in substituting any ilegal character with his hexadecimal value for the final URL&#8217;s composition.</p>
<p><span id="more-1849"></span>In addition, we will also use the <a href="http://developer.xojo.com/declare" target="_blank" rel="noopener">Declare statement</a> to access the iOS Clipboard so we can Copy the shortened URL in order to use it in any other app installed on the device.</p>
<p>Before you can start with this tutorial, make sure you have installed <a href="https://itunes.apple.com/es/app/xcode/id497799835?mt=12" target="_blank" rel="noopener"><strong>Xcode</strong></a> on your Mac. You&#8217;ll need the Simulator app, included with Xcode, in order to run any iOS app developed with Xojo (you can download and install Xcode for free from the Mac App Store). You will need also a General OAuth key to use when accessing the Bit.ly&#8217;s API exposed methods. To get your own key, you have to create an account on Bit.ly and follow the instructions found <a href="https://dev.bitly.com/get_started.html" target="_blank" rel="noopener">here</a>.</p>
<p>Of course, to follow this tutorial you also need to install Xojo on your Mac! You can always download the most recent release of <strong>Xojo</strong> from <a href="http://www.xojo.com/download" target="_blank" rel="noopener">here</a>.</p>
<h2>Designing the interface</h2>
<p>Run the Xojo IDE and select the iOS App template from the Project Chooser. As result, the IDE will create a new project that already includes the barebones items in order to have a functional App. In fact, clicking the Run button will launch the app on the Xcode&#8217;s Simulator showing the default View… but nothing else.</p>
<p>Choose the <strong>View1</strong> item on the <strong>Navigator</strong> (the leftmost column on the IDE). This action will show the project default view on the Layout Editor. Click on the Library button and you will see all the objects or graphic components (UI elements) available for you to design the user interface for your iOS apps, as shown in this picture.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1851 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/UIWidgets.png" alt="UI widgets for iOS Apps in Xojo" width="378" height="463" /></p>
<p>Drag the <a href="http://developer.xojo.com/textfield" target="_blank" rel="noopener"><strong>TextField</strong></a> control from the <strong>Library</strong> (found below the Inputs group) and drop it on the upper side of the view. Use the control handlers and the alignment guides to adjust his position and size, as shown in the following picture.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1852 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/URLField.png" alt="TextField control on iOS project" width="1024" height="324" /></p>
<p>Select the just added TextField and click on the <strong>Inspector</strong> button in order to change some properties for the control. Here is the place where you can change some attributes like the control&#8217;s name (the one used to refer the control from code), the text color, keyboard type, text alignment, font size, etc. In this case, we will change these properties:</p>
<ul>
<li><strong>Name:</strong> txtURL</li>
<li><strong>KeyboardType:</strong> URL</li>
<li><strong>PlaceHolder:</strong> http://</li>
<li><strong>Text:</strong> http://</li>
</ul>
<p>Once done, drag a <a href="http://developer.xojo.com/userguide/ios-buttons" target="_blank" rel="noopener"><strong>Button</strong></a> from the Library and place it to the right of the TextField added before. Use the control handlers to adjust their size, and push on the icon with the picture of a pencil to change the label text to &#8220;Go!&#8221;, as shown in this picture.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1853 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/BotonGo.png" alt="Adding Button UI widget to iOS app in Xojo" width="445" height="219" /></p>
<p>Besides shortening the typed URL, our iOS App will also show the corresponding webpage for that URL, something as easy as placing a <a href="http://developer.xojo.com/htmlviewer" target="_blank" rel="noopener"><strong>HTMLViewer</strong></a> control instance from the Library below the TextField, as shown in the following picture.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1854 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/HTMLViewer.png" alt="Adding HTMLViewer to iOS App in Xojo" width="704" height="720" /></p>
<p>Finally, we will add a couple of <a href="http://developer.xojo.com/ioslabel" target="_blank" rel="noopener"><strong>Label</strong></a> controls below the HTMLViewer and a second Button control. The leftmost Label control will be a simple… well… label, but the second one will reflect the shortened URL. Place these controls from the Library, adjusting their sizes and positions as shown in this picture.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1855 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/ShortenedArea.png" alt="shortenedarea" width="426" height="236" /></p>
<p>Choose the central Label, the one used to show the shortened URL, and these properties, with the help of the Inspector:</p>
<ul>
<li><strong>Name:</strong> lblShortURL</li>
<li><strong>Text:</strong> (vacío)</li>
</ul>
<p>We finished our User Interface design! (tough?) In fact, you can again click the Run button from the Xojo IDE in order to run the app on the <strong>iOS Simulator</strong>. Once again, our default View will show up and, this time, you can play with the TextField and the Buttons… but nothing will happen yet. This is normal, we have to put the code on these controls we want to execute as a reaction to some kind of user interaction (event).</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1856 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/Simulador.png" alt="simulador" width="206" height="300" /></p>
<p>Return to the Xojo IDE, stop the app execution (click on the Stop button) and change your interface designer hat with the programmer one. Yeah, it&#8217;s time to write our own subclass in charge of communicate with the Bit.ly API!</p>
<h2>Talking with Bit.ly&#8217;s API</h2>
<p>It&#8217;s time to write our communication class with the Bit.ly&#8217;s API. That&#8217;s the class responsible of making the web request (via <strong>HTTP</strong> protocol) to the exposed method by the remote API…and to receive and work with the returned data. And, when it comes with web communications where we have to asynchronously deal with the received answer, we have to use our inherited subclass from <strong>Xojo.Net.HTTPSocket</strong> in order to add the specialized behaviour over the one found on the base class.</p>
<p>Choose <strong>Insert &gt; Class</strong> to add a new Class to the project. Click on the just added class on the Navigator and change these attributes on the Inspector:</p>
<ul>
<li><strong>Name:</strong> BITLYSocket</li>
<li><strong>Super:</strong> Xojo.Net.HTTPSocket</li>
</ul>
<p>Click now the &#8216;+&#8217; button on the IDE toolbar and choose the Event Handler menu option, as shown in this picture:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1857 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/SocketEventHandler.png" alt="socketeventhandler" width="546" height="419" /></p>
<p>Select the <strong>PageReceived</strong> event on the resulting Window and click the Ok button. This action will add the event under the &#8216;Event Handlers&#8217; hierarchy for our BITLYSocket class. In fact, this event will fire, executing the associated Xojo code, every time our socket receives data as result of our HTTP requests.</p>
<p>Type these lines of code in the Code Editor for the PageReceived event handler:</p>
<pre>if HTTPStatus = 200 then
  dim data as Dictionary = xojo.data.ParseJSON( xojo.core.TextEncoding.UTF8.ConvertDataToText(content) )
  dim dataurl as Dictionary = data.Value( "data" )

  raiseevent URLShortened( dataurl.Value( "url" ) )
end if</pre>
<p>As you can see, we check the returned Status Code to make sure that our request was properly processed (integer value 200). Next, we assign the result of parsing the returned data as a <strong>JSON</strong> structure to the &#8216;data&#8217; variable, defined as a <strong>Dictionary</strong> type. (Xojo makes it really easy to interchange JSON and Dictionary structures/objects!)</p>
<p>The third line of code is the one in charge of creating the &#8216;dataurl&#8217; Dictionary variable, and that will point to the Dictionary that really has the data we are interested in: the shortened URL. Finally, we raise a new event on our own class, passing the shortened url as Text.</p>
<p>You can find that the keys used in the Dictionary variables to retrieve the associated data, are the ones provided by Bit.ly in the response data, whose structure is documented and available on the Bit.ly&#8217;s API website.</p>
<p>To define a new event for our class, make sure that the BITLYSocket item is selected on the Navigator and click again on the &#8216;+&#8217; button on the IDE Toolbar. This time, choose the &#8216;Event Definition&#8217; menu option, as shown in this picture:</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1858 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/SocketEventDefinition.png" alt="socketeventdefinition" width="526" height="406" /></p>
<p>Unlike when we add a new Method to a class, the new event definition just allows us to write its signature; I mean, the event name and the parameters it will receive (if any) and/or the returned type (if proceed). After all, the code implementation for the event is a job of the Class consumer: the instances created from the class that decide to add the event.</p>
<p>As for our class, the added event will be responsible for passing the shortened URL to the class consumer (as we have seen in the previous code snippet), so the instance can decide what to do with the received data. In our app, this will be assigning the shortened URL (received as Text) to the central Label of our user interface.</p>
<p>Choose the added event and modify the following properties on the Inspector:</p>
<ul>
<li><strong>Event Name:</strong> URLShortened</li>
<li><strong>Parameters:</strong> URL as Text</li>
</ul>
<h3>HTTP Request on iOS</h3>
<p>With the BITLYSocket selected on the Navigator, we are going to add a new Method. This will be the entry point for the class consumer to pass the URL to be shortened. For that, click again on the &#8216;+&#8217; button from the IDE toolbar and choose the Method menu option.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1860 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/SocketMethod.png" alt="socketmethod" width="516" height="408" /></p>
<p>Type the following values on the associateed Inspector:</p>
<ul>
<li><strong>Method Name:</strong> ShortURL</li>
<li><strong>Parameters:</strong> URL as Text</li>
</ul>
<p>And type the following code on the Code Editor for the just added method (ShortURL):</p>
<pre>Declare Function CFURLCreateStringByAddingPercentEscapes lib "Foundation" _
  (allocator as Ptr, origString as CFStringRef, charactersToLeaveUnescaped as CFStringRef, _
  legalURLCharactersToBeEscaped as cfStringRef, encoding as uint32) as CFStringRef

dim encodedURL as Text = CFURLCreateStringByAddingPercentEscapes(nil,url,nil,nil,&amp;h08000100)

dim compossedURL as Text = "https://api-ssl.bitly.com/v3/shorten?access_token=" _
  + kToken + "&amp;longUrl=" + encodedURL

me.Send("GET", compossedURL)</pre>
<p>Here is where we find the first Declare statement on our code! In fact this one is responsible for calling the CFURLCreateStringByAddingPercentEscapes function in order to substitute the illegal characters on a URL with their hexadecimal values. This is done with the second line of code, where we call the function, assigning the result to the &#8216;encodedURL&#8217; variable.</p>
<p>The third line of code is where we compose the final URL in order to call the Bit.ly API&#8217;s method, putting the OAuth key, present here as the kToken constant (define your own class constant, and assign your OAuth key to it), and also adding the variable that points to the URL, with all their characters correctly escaped, to the end of the string.</p>
<p>The last line of code is where we make the request itself, using the Send method from the HTTPSocket base class. The first parameter is the method we want to use for the request (&#8220;GET&#8221; in this case), and the second parameter is the URL for the HTTP request.</p>
<p>We have finished our class definition!</p>
<h2>Putting all to work together</h2>
<p>Let&#8217;s add an instance of our BITLYSocket class to the app. For that, select the <strong>View1</strong> item from the Navigator and, then, drag the BITLYSocket from the Navigator over the lower part of the Layout Editor. This action will show the Shelf, where you can drop the item in order to create a new instance named BITLYSocket1 (this one will be shown also under the View1 hierarchy on the Navigator).</p>
<p>Select the BITLYSocket1 instance under the Controls section of View1 on the Navigator and add a new Event Handler. From the resulting window, you&#8217;ll see the event defined by us. Choose this event (URLShortened) and click the Ok button in order to add it to the BITLYSocket1 instance.</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1861 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/BITLYSocketEvent.png" alt="bitlysocketevent" width="984" height="325" /></p>
<p>Type the following line of code in the associated Code Editor for the Event Handler:</p>
<pre>lblShortURL.Text = url</pre>
<p>This is the way we asign the received text (the shortened URL) to the Text property of the Label control instance.</p>
<p>But for this Event Handler to fire, we need to make the HTTP request in first place! Select the button Button1, add the Action Event Handler (the one that fires when the user pushes the button), and type the following code:</p>
<pre>HTMLViewer1.LoadURL(txtURL.Text)
BITLYSocket1.shortURL(txtURL.Text)</pre>
<p>Firstly, we load the web page for the URL typed on the TextField and, with the second line of code, we call the ShortURL method passing the URL as parameter. This line of code is what puts our communication socket to work!</p>
<p>Run again the app on the iOS Simulator and type some URLs. You&#8217;ll see that now the app load the corresponding webpage and shows the shortened URL on the lower label of the interface!</p>
<p><img loading="lazy" decoding="async" class="size-full wp-image-1862 aligncenter" src="https://blog.xojo.com/wp-content/uploads/2016/09/FinalWorkingApp.png" alt="finalworkingapp" width="752" height="1094" /></p>
<div>While the HTTPSocket subclass will work under iOS 9 and later, this is not the case for the HTMLViewer when deploying the app under iOS 9 or the more recent iOS 10. The cause is that Apple enforces the use of HTTPS over HTTP when loading webpages or when using remote APIs (the <a href="http://bit.ly/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=http://bit.ly&amp;source=gmail&amp;ust=1474553636364000&amp;usg=AFQjCNHtiDcInDMVob6Wz0zaMHgSV6XwQQ" rel="noopener">bit.ly</a> API uses HTTPS, so no problem with this part).</p>
<p>As for the load of webpages on the HTMLViewer, you simply have to implement the solution published by Paul Lefebvre <a href="http://blog.xojo.com/2016/07/27/app-transport-security-for-ios/">in this post</a>.</div>
<p>Basically, create a text file with the following content and drag the file over the Project Browser in order the Xojo IDE can merge it with the global Info.plist created during the app compilation:</p>
<p>&lt;?xml version=&#8221;1.0&#8243; encoding=&#8221;UTF-8&#8243;?&gt;<br />
&lt;!DOCTYPE plist PUBLIC &#8220;-//Apple//DTD PLIST 1.0//EN&#8221; &#8220;<a href="http://www.apple.com/DTDs/PropertyList-1.0.dtd" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=en&amp;q=http://www.apple.com/DTDs/PropertyList-1.0.dtd&amp;source=gmail&amp;ust=1474553636364000&amp;usg=AFQjCNHEpNh4jyo7MbQ_qdCTcVP7-T-l0g" rel="noopener">http://www.apple.com/DTDs/<wbr />PropertyList-1.0.dtd</a>&#8220;&gt;<br />
&lt;plist version=&#8221;1.0&#8221;&gt;<br />
&lt;dict&gt;<br />
&lt;key&gt;NSAppTransportSecurity&lt;/<wbr />key&gt;<br />
&lt;dict&gt;<br />
&lt;!&#8211; Include to allow all connections; avoid if possible &#8211;&gt;<br />
&lt;key&gt;NSAllowsArbitraryLoads&lt;/<wbr />key&gt;<br />
&lt;true/&gt;<br />
&lt;/dict&gt;<br />
&lt;/dict&gt;<br />
&lt;/plist&gt;</p>
<h2>Copying to the Clipboard</h2>
<p>There is one last detail: If you tap on the Copy button… it simply doesn&#8217;t work. We need to put some code here too inside the Action Event Handler.</p>
<p>Choose the Button2 item on the Project Browser and add the Action Event Handler. Type the following lines of code to the associated Code Editor:</p>
<pre>declare sub setValue lib "UIKit" selector "setValue:forPasteboardType:" _
  (obj_id as ptr, value as ptr, pasteboardType as CFStringRef)
declare function generalPasteboard lib "UIKIt" selector "generalPasteboard" (clsRef as ptr) as ptr
declare function NSClassFromString lib "Foundation" (clsName as cfstringref) as ptr
declare function stringWithString lib "Foundation" selector "stringWithString:" _
  (clsRef as ptr, str as cfstringref) as ptr

setValue(generalPasteboard(NSClassFromString("UIPasteboard")), _
  stringWithString(NSClassFromString("NSString"), lblShortURL.Text), "public.text")</pre>
<p>This is the solution that allows our app to copy the shortened URL text to the iOS Clipboard. This snippet of code has been extracted from <a href="https://forum.xojo.com/18936-clipboard/2" target="_blank" rel="noopener">this thread</a> on the Xojo forums, showing once more how great is the Xojo&#8217;s community!</p>
<p>Now, every time you tap the Copy button you&#8217;ll find the shortened URL on the Clipboard.</p>
<p>In short, in this tutorial we have seen how easy it is to make Web API requests from our Xojo iOS Apps, work with the returned data as JSON, and how powerful and useful the Declare statement is, in order to work directly with the methods and functions from the Cocoa Touch and Foundation frameworks from our Xojo code.</p>
<p>You can <a href="https://www.youtube.com/watch?v=z5iVHkdBTNA" target="_blank" rel="noopener">watch the video</a> (in Spanish only) that talks you though this example.</p>
<p><em>Javier Rodri­guez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has used Xojo since 1998. He is in charge of AprendeXojo.com and the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.</em></p>
<p><a href="http://www.aprendexojo.com/2016/09/tutorial-ios-crear-un-acortador-de-url/" target="_blank" rel="noopener">*Read this post in Spanish</a></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Test Web Services with RESTy</title>
		<link>https://blog.xojo.com/2015/08/21/test-web-services-with-resty/</link>
		
		<dc:creator><![CDATA[Paul Lefebvre]]></dc:creator>
		<pubDate>Fri, 21 Aug 2015 00:00:00 +0000</pubDate>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[HTTPSocket]]></category>
		<category><![CDATA[REST]]></category>
		<guid isPermaLink="false">http://blogtemp.xojo.com/2015/08/21/test-web-services-with-resty/</guid>

					<description><![CDATA[Use this simple Xojo project to test REST web service calls.]]></description>
										<content:encoded><![CDATA[<p><strong><em>This post was updated in March 2023 in <a href="https://blog.xojo.com/2023/03/07/testing-rest-based-web-services/">Testing REST-based Web Services</a>.</em></strong></p>
<p>Communicating with web services is fun and easy with Xojo. But sometimes it&#8217;s not so easy to test the actual REST API calls. As part of preparing materials for the HTTPSocket webinar, I created a simple app in Xojo that lets you test REST APIs. I call it RESTy.</p>
<p><span id="more-325"></span></p>
<p>RESTy uses <a href="http://developer.xojo.com/xojo-net-httpsocket">Xojo.Net.HTTPSocket</a> to send a request to a web service and get a result. If the result is text (JSON, for example) it displays in the <strong>Response</strong> tab. Here, I am calling the <a href="http://developer.xojo.com/eddies-electronics-web-service">Eddie&#8217;s Electronics web service</a> to return a list of all the customers by specifying the URL and clicking the Fetch button:</p>
<p><img decoding="async" style="width: 525px;" src="https://blog.xojo.com/wp-content/uploads/2015/08/RESTy.pngt1466486449161ampwidth525" sizes="(max-width: 525px) 100vw, 525px" alt="RESTy" width="525" /></p>
<p>For other data (binary data such as pictures) you can use the Fetch to File button to save the request to a file.</p>
<p>The Authentication tab is used to provide Basic Authentication should the web service require it.</p>
<p>The Request Content tab can be used to provide Content data that the request might need. For example, the <a href="http://demos.xojo.com/EEWeb/" target="_blank" rel="noopener">Eddie&#8217;s Electronics</a> web service also lets you request the details for a specific customer by providing simple JSON containing the customer ID. For example:</p>
<pre>{"ID": 10039}</pre>
<p>You can put this JSON in the Request Content tab and then call the web service to get the customer information using this URL (be sure to select POST as the method type):</p>
<pre>http://demos.xojo.com/EEWS/index.cgi/special/GetCustomer</pre>
<p>To be sure, RESTy is very simple, but you have the source code so feel free to add features to it!</p>
<ul>
<li><a href="http://files.xojo.com/BlogExamples/RESTy.xojo_binary_project.zip">Download RESTy Project</a></li>
</ul>
<p>If you&#8217;re looking for something with more features, there are also commercial products to test REST web services. Here are a few:</p>
<ul>
<li><a href="https://luckymarmot.com/paw">Paw</a></li>
<li><a href="https://itunes.apple.com/us/app/do-http/id887133786?mt=12">Do Http</a></li>
<li><a href="http://restscratchpad.com">REST Scratchpad</a></li>
</ul>
<p>If you know of others, let me know in the comments.</p>
<p>Want to learn more about Xojo.Net.HTTPSocket and web services?</p>
<p><span id="hs-cta-wrapper-80e618e0-e34d-4b07-8ed3-d3ac8eed66ae" class="hs-cta-wrapper"><span id="hs-cta-80e618e0-e34d-4b07-8ed3-d3ac8eed66ae" class="hs-cta-node hs-cta-80e618e0-e34d-4b07-8ed3-d3ac8eed66ae"><!-- [if lte IE 8]>


<div id="hs-cta-ie-element"></div>


<![endif]--> <a href="http://developer.xojo.com/webinar-httpsocket" target="_blank" rel="noopener"><img loading="lazy" decoding="async" id="hs-cta-img-80e618e0-e34d-4b07-8ed3-d3ac8eed66ae" class="hs-cta-img aligncenter" style="border-width: 0px; margin: 0 auto; display: block; margin-top: 20px; margin-bottom: 20px;" src="https://blog.xojo.com/wp-content/uploads/2015/05/80e618e0-e34d-4b07-8ed3-d3ac8eed66ae.png" alt="Watch the HTTPSocket Video" width="635" height="97" align="middle" /></a> </span><script src="https://js.hscta.net/cta/current.js" charset="utf-8">// <![CDATA[
<script type="text/javascript"><![CDATA[ hbspt.cta.load(608515, '80e618e0-e34d-4b07-8ed3-d3ac8eed66ae', {}); // ]]&gt;</script></span><br />
<!-- end HubSpot Call-to-Action Code --></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
