I am trying to send an array of guids as postdata using a javascript function. The recieving aspx page needs to process this data.
The javascript that calls the page is as following:
function(webadress, guidarray) {
var params = 'menubar=no,status=no,toolbar=no,resizable=no, scrollbars=no';
var win = document.createElement("form");
win.target = 'Map';
win.method = 'POST';
win.action = webadress;
var winInput = document.createElement('input');
winInput.type = 'text';
winInput.name = 'guidcollection';
winInput.value = guidarray;
win.appendChild(winInput);
win.setAttribute("target", "_blank");
window.open(webadress, '', params);
win.submit();
}
The aspx page attempts to read the post data as following:
protected void Page_Load(object sender, EventArgs e)
{
object PostGuids = HttpContext.Current.Request.Form["guidcollection"];
// Do something with PostGuids
}
Somehow it fails, and when i debug the aspx page I see that HttpContext is not defined. Using fiddler I can determine that the sessionId is not set. I see the message 'This request did not send any cookie data.' in the Cookies tab.
What can i do to receive the post data? One of the requirements for the website is that cookie data on the client is not allowed. Is it possible to receive Post data without a sessionId? or should i look for alternatives like ViewState? Using a query string won't work because the length of the data will exceed the 2048 character limit of a querystring.
I have managed to get this working with the following changes:
function(webadress, guidarray) {
var params = 'menubar=no,status=no,toolbar=no,resizable=no, scrollbars=no';
var win = document.createElement("form");
win.target = 'Map';
win.method = 'POST';
win.action = webadress;
var winInput = document.createElement('input');
winInput.type = 'text';
winInput.name = 'guidcollection';
winInput.value = guidarray;
win.appendChild(winInput);
document.body.appendChild(win);
window.open(webadress, 'Map', params);
win.submit();
}
and server side:
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.Form.HasKeys())
{
object PostGuids = this.Request.Form["guidcollection"];
// Do something with PostGuids
}
}
I still have no idea why the HttpContext remains undefined, but this way i can access the guid data correctly. If some one can explain that to me, i'll be glad to accept that as the answer.
Related
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});
}
I want to POST some data to an aspx page by javascript.
I send POST-httprequest to my aspx page and receive the request in my aspx page.
But the problem is that there is no parameter in my request. In other words my request.form is empty!
Here is my javascriptcode:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var http = new XMLHttpRequest();
var url = "https://myserver/1.aspx";
var params = "param1=something¶m2=somethingelse";
http.open("POST", url, false);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.send(params);
And here is my aspx page:
<%
protected void Page_Load(object sender, EventArgs e)
{
var first = Request.Form["param1"];
var second = Request.Form["param2"];
var tot = first + second;
}
%>
This method work fine with http-GET-request!
Have any idea what the problem is?
Answer!:
The problem was not related to server and request handling in server!
Actually the problem was in var url = "https://myserver/1.aspx";
If you put ip there, the client will not send data, but it does not return error too!
Try this :
http.send(JSON.stringify({ "param1": "something", "param2": "something" }));
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.
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.
I have a custom ActionResult that I pass in a url string to and it will stream a file back to me. How would I call this from Javascript file? Since I have to pass a string I don't think I can use jQuery's $.post() or .ajax() methods but I could be wrong. I also can not use Razor's #Html.ActionLink method for reasons involving the ? Here is my code.
public class ReportResult : ActionResult
{
private readonly string _fileName;
public ReportResult(string fileName)
{
_fileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
var cd = new ContentDisposition
{
FileName = _fileName,
Inline = false
};
var response = context.HttpContext.Response;
response.ContentType = "application/pdf";
response.Headers["Content-Disposition"] = cd.ToString();
using (var client = new WebClient())
using (var stream = client.OpenRead(_fileName))
{
stream.CopyTo(response.OutputStream);
}
}
}
The Controller Method that references it.
public ActionResult DownloadPdf(string filePath)
{
return new ReportResult(filePath);
}
So the reason why I was having issues with the file opening up in a window rather than downloading was due to the Controller and Action method part of the url string getting cut off before it was getting passed to location.href in the Javascript. Below is the new Javascript that will open the url and immediately download the PDF file.
location.href = "/Controller/DownloadPdf?filePath=" + pdfUrl;
Thanks to #SLacks in the comments for some guidance.