Porting function from java (Android) to AngularJs - javascript

I'm trying to write an old native Android app with Ionic and I need help for the http request. I'm newbie in AngularJS (js too).
My Android code has a function like:
String address = "http://www.example.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(responsegetEntity().getContent()));
StringBuilder sBuilder = new StringBuilder();
String sLine = "";
while ((sLine = rd.readLine()) != null) {
sBuilder.append(sLine).append("\n");
}
String sContent = sBuilder.toString();
(...parsing sContent...)
} catch (Exception e) {
//something
}
and if there are more then one page I call a function like
String address = "http://www.example.com/result.do?page="+ iPage;
HttpPost post = new HttpPost(address);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("param", sParam));
Cookie ck = client.getCookieStore().getCookies().get(0);
pairs.add(new BasicNameValuePair("param_ck", ck.getValue()));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
(..parsing..)
}
So, I read the html content of a webpage (I'm not the owner) and I do somethings with that.
I tried $http.post but I'm not sure if it's the same
.factory('Service', function($q,$http) {
return {
getResult: function(param) {
var q = $q.defer();
var address = "http://www.example.com";
var sParam = "param";
$http({
url: address,
method: "POST",
data: {
'param' : sParam
}
})
.then(function(response) {
(...)
q.resolve(position);
},
function(error) {
(...)
q.reject(error);
});
return q.promise;
}
};
});
PS: I get the
No 'Access-Control-Allow-Origin' header is present on the requested resource.
with that.
Can you help me?

I am not entirely sure why you don't get a similar error with your Android code, or even if you were supposed to, as I am not familiar with native Android itself. But the reason that you get this with Angular in Ionic is that the server requires to implement CORS to get rid of that.
From MDN:
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which the first resource itself serves. For example, an HTML page served from http://domain-a.com makes an src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.

Related

How do I parse an image sent from Retrofit API from Android (multipart/form) in Python's Flask

I am sending my image as a part of Form Data through Retrofit API. There are no issues loading the image. I am trying to get this image in a Python Flask server.
My python code is not responding the expected way. I have tested my Python code with a JavaScript frontend application and the python server responds as expected. I believe the issue is parsing the multipart/form file which I receive from Android.
There are no network issues, I am able to log the requests. The detectFace() function is not responding as expected for the same image sent through both clients, VueJs and Android.
Any ideas will be appreciated.
Here is the android code for uploading:
private void sendImageToServer() {
File imageFile = loadImageFromStorage(tempImagePath);
RequestBody reqBody = RequestBody.create(MediaType.parse("image/jpeg"), imageFile);
MultipartBody.Part partImage = MultipartBody.Part.createFormData("file", "testImage", reqBody);
API api = RetrofitClient.getInstance().getAPI();
Call<TestResult> upload = api.uploadImage(partImage);
upload.enqueue(new Callback<TestResult>() {
#Override
public void onResponse(Call<TestResult> call, Response<TestResult> response) {
if(response.isSuccessful()) {
TestResult res = response.body();
String jsonRes = new Gson().toJson(response.body());
String result = res.getResult();
Log.v("REST22", result);
}
}
#Override
public void onFailure(Call<TestResult> call, Throwable t) {
Log.v("REST22", t.toString());
Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
Here is Python code:
#app.route('/detectFaces/', methods=['POST'])
def detectFaces():
img = request.files.get('file')
print('LOG', request.files)
groupName = 'random-group-03'
result = face.detectFaces(img, groupName)
print('RESULT', result)
return {'result' : result[0]}
VueJs - alternate working frontend (REST client):
sendImage(img) {
console.log(img)
var form = new FormData();
form.append('file', img, 'testImage')
axios.post(this.baseUrl + 'detectFaces/?groupName=random-group-03', form)
.then(res => {console.log(res.data); this.log = 'Detected face ids: \n ' + res.data.result});
}

How to get responsetext from a Page with Post method using XMLHttpRequest in asp.net?

I have a web page which sends a video file/blob to another web page in the using FormData using POST method and XMLHttpRequest. I want to return the response as string from the Posted URL in calling function. i.e after successfull upload file i want to return string to the caller.
index.aspx:
function SendFile(blob)
{
var file = new File([blob], "testfile123.webm");
var oData = new FormData();
oData.append("file", file,"testfile.webm");
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload.aspx", true);
oReq.onload = function (oEvent)
{
if (oReq.status == 200)
{
alert("Uploaded"+oReq.responseText);
}
else {
alert("Error");
}
};
oReq.send(oData);
}
Upload.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string folderPath = GetUploadFolderPath();
string filename = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + ".webm";
HttpFileCollection fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile postedFile = fileCollection[i];
var filePath = folderPath + filename; //postedFile.FileName;
postedFile.SaveAs(filePath);
}
}
In above code the file is created at specified location all works fine.I know its not possible in Page_Load event. please suggest correct method to send responsetext/string after file upload.
Help Appreciated.
This is a scraped together example on how to target specific functions inside aspx with jquery.ajax using vb.net. Sadly I am not fluent in C#.
Note that if you are using an ancient version of .net (two or lower), you have to add System.Web.Extensions in your web.config to make it work. Depending on the IIS either as httpModules or as modules.
AJAX.aspx
<WebMethod(EnableSession:=True)> _
Public Shared Function abc(def As String) As Boolean
''REM: Do stuff
Return True
End Function
xhr call using jquery
$.ajax({
type: "POST",
url: "AJAX.aspx/abc",
data: "{'def':'test'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(response){...},
error: function(jqXHR, textStatus, errorThrown){...}
});
Yet, I still recommend to use generic handlers, like also shown here. It is more clean, slim and offers more control on what you actually want to do. Also the System.Web.Extensions are not required.

Better ways of catching Request and Response Headers?

Im currently working in MVC and I have what I see as crude ways of catching response and request headers on my pages.
First is Response headers which I currently handle on the page
$(document).ready(function () {
var name = "Comp";
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var myHeader = req.getResponseHeader(name);
alert(myHeader);
});
it makes a new request when the document is ready which could ruin the header if it isn't pretty static (wouldn't work if the header were to change between the sessions) but it currently workes.
I do catch the Request header inside of the controller
public new ActionResult Profile()
{
var head = Request.Headers.GetValues("Comp");
try
{
if (head != null)
{
string id = head.First();
ViewBag.message = head.First(); //controll
return View();
}
}
catch
{
ViewBag.message = "Header method Failed";
}
return View();
}
Now I wonder if there are better ways of doing this. Someone enlighten me.

C# Httpwebrequest detection

What ways are there for a website to detect automated connections made through C# Httpwebrequest?
Such as c#'s default user-agent? Operating System? or what..
have this problem with any other language, just C#?
I'm being blocked from accessing a certain website using Httpwebrequest, I don't
Also it's definitely not my IP address & nor are there any faults in my code as I've tested connections to other websites which work just fine.. Also I stated above I can make connections to the website using C++, C, Vb.net, Java, Python & so on, there is also no difference in header information either.
EDIT:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://services.runescape.com/m=hiscore_oldschool/overall.ws");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "user1=Zezima&submit=Search";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
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 ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
private const string Url = "http://services.runescape.com/m=hiscore_oldschool/overall.ws";
private static HttpWebRequest BuildWebRequest()
{
var request = WebRequest.Create(Url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 40000;
request.ServicePoint.Expect100Continue = true;
string body = "user1=Zezima&submit=Search";
byte[] bytes = Encoding.Default.GetBytes(body);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
return request;
}
static void Main(string[] args)
{
try
{
HttpWebRequest request = BuildWebRequest();
var response = request.GetResponse() as HttpWebResponse;
var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.Write("Success - " + response.StatusCode);
}
catch (Exception e)
{
Console.Write(e);
}
}
I can take the response from the website. It is not empty.

Send a file with POST request using C# to Node.js server

i've a node.js local server and i want to upload a file from WP to this server using a POST request. Node.js server can parse a multipart/form-data - read data from "files" and "fields" and save the file in a local folder using node-formidable library.
How i can send a request like this (using the web form) using C# for WinRT?:
https://www.imageupload.co.uk/images/2015/04/27/Cattura.png
I try with this code:
public async Task<string> SendWithMultiPartForm()
{
string servResp = "";
using (var content = new MultipartFormDataContent(boundary))
{
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
content.Add(new StreamContent(await fileToSend.OpenStreamForReadAsync()), "files", "files");
HttpClientHandler handler = new HttpClientHandler();
cookieContainer = new CookieContainer();
handler.CookieContainer = cookieContainer;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, SiteURI);
request.Headers.ExpectContinue = false;
request.Content = content;
httpClient = new HttpClient(handler);
HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
servResp = await response.Content.ReadAsStringAsync();
}
return servResp;
}
but the result is:
https://www.imageupload.co.uk/images/2015/04/27/Cattura2.png
Can anybody help me? Thanks!

Categories