What is the relevant code for getInputStream() in Swift 5? - swift

In Android Studio, I use this code to get data from server
url = new URL(url);
HttpURLConnection connection = null;
try
{
HttpURLConnection.setFollowRedirects(false);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(10000);
connection.setInstanceFollowRedirects(false);
InputStream inputStream = connection.getInputStream();
this.header = connection.getHeaderFields();
this.status = connection.getResponseCode();
}
In Swift 5, I'm able to perform similar task by using URLSession.shared.dataTask(), but I couldn't find anything to replace InputStream inputStream = connection.getInputStream().
After I did some research on Swift 5 inputStream and outputStream, I'm getting more confused, can anyone provide some sample on how to replace this?

Use uploadTask(withStreamedRequest in order to work with streams https://developer.apple.com/documentation/foundation/urlsession/1410934-uploadtask

Related

How to parse AEM DAM JSON InputStream and create JSON Object

I have a requirement where-in I have to read the JSON file which exists in AEM DAM. So, I have created a query to read the JSON file in inputStream. With the below line of code, i could get the JSON file in Input Stream. Now, I need to know If there is any standard library to read the input stream and create the JSON Object?
InputStream is = asset.getOriginal().getStream();
There are many libraries for serializing/deserializing JSON in java, the most notable is Google’s Gson: https://github.com/google/gson
I’ve used gson in all my AEM projects that require JSON manipulation. That does not mean you can’t use another library.
As mentioned above there are many libraries like Google’s Gson, Jackson an etc. I think the below code snippet can help you,
public JSONObject getJsonFromFile(ResourceResolver resolver,String filePath){
JSONObject jsonObj=new JSONObject();
Resource resource= resolver.getResource(filePath);
try {
Node jcnode = resource.adaptTo(Node.class).getNode("jcr:content");
InputStream content=jcnode.getProperty("jcr:data").getBinary().getStream();
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new
InputStreamReader(content,StandardCharsets.UTF_8));
while ((line = br.readLine()) != null) {
sb.append(line);
}
jsonObj = new JSONObject(sb.toString());
}catch (RepositoryException | JSONException | IOException e) {
LOGGER.error(e.getMessage(),e);
}
return jsonObj;
}

CRM 2013: Deserializing within a sandboxed plugin

I have an XML string that I would like to deserialize into a strongly typed class. The below code works great until I put it into a sandboxed plugin, at which point I get a FileIOPermissions error because I am using the StringReader class. I am having issues trying to deserialize without using StringReader. Does anyone have a good alternative?
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
DataContractSerializer serializer = new DataContractSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
using (XmlTextReader xmlReader = new XmlTextReader(reader))
{
if (serializer.IsStartObject(xmlReader)) //Throws FileIOPermissions error
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)(serializer.ReadObject(xmlReader));
}
}
}
Try the following which I've run successfully in a sandbox plugin:
byte[] binary = Convert.FromBase64String(configurationWebResource.Attributes["content"].ToString());
resourceContent = UnicodeEncoding.UTF8.GetString(binary);
XmlSerializer serializer = new XmlSerializer(typeof(ViewSecurityConfiguration));
using (StringReader reader = new StringReader(resourceContent))
{
currentViewSecurityConfiguration = (ViewSecurityConfiguration)serializer.Deserialize(reader);
}

Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.
The old HttpClient code looks something like this:
PostMethod postMethod = null;
int responseCode = 0;
try{
HttpClient httpClient = new HttpClient();
postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
...
postMethod.addParameter(paramName, request);
responseCode = httpClient.executeMethod(postMethod);
...
}
And here are my HttpComponents replacements:
HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
HttpClient httpClient = new DefaultHttpClient();
postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
...
BasicHttpParams params = new BasicHttpParams();
params.setParameter(paramName, request);
postMethod.setParams(params);
httpResponse = httpClient.execute(postMethod);
responseCode = httpResponse.getStatusLine().getStatusCode();
...
}
The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:
ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
throw new IOException("Could not construct ServletRequestContext object");
It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?
Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.
To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.
To send a form entity, for example:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);

Threading in MonoTouch with webrequest and uialertview

I access a website and retrieve some data using HttpWebRequest and I need a UIAlertView with a UIActivityIndicatorView to display while it retrieves said data. However, it just dims the screen and doesn't show the alert until it's too late. I've read other threading related questions here and can't figure out how to resolve this. I tried using ThreadPool, InvokeOnMainThread, Tasks, all of which have not worked.
EDIT:
HttpWebRequest url = (HttpWebRequest)WebRequest.Create ("maps.googleapis.com/maps/api/place/search/..);
HttpWebResponse webResp = (HttpWebResponse)url.GetResponse (); JsonValue jVal =
JsonObject.Load (webResp.GetResponseStream ());
JsonObject jObj = (JsonObject)jVal;
I have the above code, if it will properly format for me, how would I convert that to use WebClient? Can you still get JSON and such from it?
It's often a lot easier (and less error prone) to use WebClient and one of it's *Async methods than using HttpWebRequest.
Here's an example to download and show a small image.
WebClient client = new WebClient ();
var wait = new UIActivityIndicatorView (View.Bounds);
client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => {
byte[] result = e.Result;
if (result != null) {
NSData data = NSData.FromArray (e.Result);
UIImage img = UIImage.LoadFromData (data);
InvokeOnMainThread (delegate {
ShowImage (img);
wait.StopAnimating ();
});
}
};
wait.StartAnimating ();
client.DownloadDataAsync (new Uri (url));
EDIT (for updated question)
For streams you can use WebClient.OpenReadAsync and the OpenReadCompleted event.

Strange Status Code From Apple Receipt Verification Sandbox

I make a post request of base64 encoded data to the receipt verification address as follows (this is in C#):
var postSerializer = new JavaScriptSerializer();
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Receipt);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
var temp = new Dictionary<string, string>();
temp.Add("receipt-data", returnValue);
string jsonReceipt = postSerializer.Serialize(temp);
request.Method = "POST";
request.ContentType = "application/json";
byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(jsonReceipt);
request.ContentLength = postBytes.Length;
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(postBytes, 0, postBytes.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
I'm pretty sure things are in the right format because I'm not getting any exceptions back
from the apple receipt verification endpoint. The entirety of the response I get back is
{status : -42352}
And I can't find out what this error means anywhere. Does anyone know what this means or if there's an error in my code?
Just solved the same problem. Got the solution from here: Verify receipt for in App purchase
The problem was in post encoding. When I encoded post on my server using
$receipt = json_encode(array("receipt-data" => base64_encode($receiptdata)));
I had the same -42352 status. When I used my own function for encoding on iPhone - everything worked! Magic...