asynctask setRequestMethod to post not working - android

I am trying to make a POST request in an AsyncTask, but the request method stays as GET all the time.
I have this issue since I moved the HTTP request to AsyncTask, the same code worked before, when it was in the UI thread.
The doInBackground code is below:
protected String doInBackground(String... string) {
httpPostToArduino (string[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute ();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute (s);
}
public void httpPostToArduino(String message){
curArd1UrlString="http://myprivateurl.com";
URL url = null;
try {
url = new URL (curArd1UrlString);
} catch (MalformedURLException e) {
e.printStackTrace ();
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
StringBuilder result = new StringBuilder (); //test
try {
urlConnection = (HttpURLConnection) url.openConnection ();
//Set header content
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization","password");
urlConnection.setDoOutput(true);
//Set body content
OutputStreamWriter os = new OutputStreamWriter (urlConnection.getOutputStream());
os.write(message.toString ());
os.flush();
InputStream in = new BufferedInputStream (urlConnection.getInputStream ());
reader = new BufferedReader (new InputStreamReader (in));
//Read the first line of the response - just the JSON
result.append (reader.readLine ());
//The below WHILE reads all the content of the response message, but we only need the first line
String ReceivedJSON = result.toString ();
JSONObject parentObject = new JSONObject (ReceivedJSON);
In the debugger, under urlConnection, for method field, it is always GET. Below a snip from debugger mode, to be clearer.
I get a response after each request, but the response depends on the body content of the POST request.
What should I change in the code in order to change the request method to POST?

I had the same Problem, for me it happened, because I did not specify the full URL path.
There are two ways to fix this. The first way is to specify the full url (with file.php at the end) and the second way is to rewrite the url in the web server config.
I fixed it by rewriting the url in my web server. This is for nginx.
This adds .php to the end of the requested URL.
location /api {
rewrite ^(/api/.*)/(\w+) $1/$2.php last;
}
For example you have the Url http://example.com/api/v1/file . After specifying the rewrite this url will be rewritten to http://www.example.com/api/v1/file.php

Related

With Android you can transfer data to any site's form and trigger the send button

hello any site you want to log in form with an Android app in the background. How I can do this process, but I did not find a result if you can help me, thank you in advance.
more examples
Any educational institution has a student add form. I want to send my student information from my own database to this form
You can create AsyncTask class to submit the form data to the URL either using POST or GET.
for example:
`
class NetworkActivity extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String.. params)
{
try{
Url url = new URL("Your URL Here");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.requestMethod("POST");
connection.setInstanceFollowRedirects(false);
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write("Form data here"+params[0]); // write form data here e.g. studentname=XYZ&rollno=123
InputStream is = connection.getInputStream();
BuffredReader br = new BufferedReader(new InputStreamReader(is));
//Fetch the output into a String
StringBuilder output = new StringBuilder();
while((line=br.readLine())!=null)
{
output.append(line);
}
return output.toString();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
protected OnPostExecute(String result)
{
//Process the output here.
}
}
`
Now create a new object of this class and call the execute function the initiate the Network activity.
new NetworkActivity().execute("form data");

Send data from Android Studio to server using url

I have an application created in Android Studio with API 28. I also have a php file (http: //mydomain/receptor.php) that collects data from a url of the type (http: //mydomain/receptor.php? Userid = 23 & points = 123) and saves them in the database. What I want is to know how I can send those urls from my application. I have tried different things but I can not get the application to activate the url. I do not need a response from the server in the application, I just need to activate the url. What is the easiest way to do it? Thank you!!!
You should run the code in a separate thread, paste this in your Activity Class
public class HTTPget extends AsyncTask<String , Void ,String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(150000); //milliseconds
urlConnection.setConnectTimeout(15000); // milliseconds
urlConnection.setRequestMethod("GET");
urlConnection.connect();
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
And you execute the code by calling .execute() whenever you want to execute it
new HTTPget().execute("http://mydomain/receptor.php?Userid=23&points=123");

how can send a json frame to mysever hear i can reserve a json and i wnd send the data

I posted the code I used for reading the data from my server but I don't know how to send a json frame to the server.
I want to send the data string.
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.connect();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
return buffer.toString();
I would assume that you are trying to post some JSON Object to a URL,
While using HttpURLConnection for connection you can set to its instance that this is a POST header request, if you are indeed posting something on that URL.
After that you can use DataOutputStream instance to write(POST) your JSON data something like this.
I have written a snippet which you can check, the code is also available on Github
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
/**
* Kindly change this url string with your own, where you want to post your json data
*/
URL url = new URL("");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
// when you are posting do make sure you assign appropriate header
// In this case POST.
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
// like this you can create your JOSN object which you want to send
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("email", "dddd#gmail.com"); //dummy data
jsonObject.addProperty("password", "password");// dummy data
// And this is how you will write to the URL
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This code uses apache-common-io, to get the String from the input stream, if you would like you can change that.

Write JSON response to a text view

I am authenticating an external system via a REST API. The http authentication request is of the Basic Authorization form. The response is in JSON format.
I am running this code under an AsyncTask.
url The GET url of the API.
credentials is the authentication credentials. It is a string.
response is the text view.
getmessage is a string variable.
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
// I am reading the response here,
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
getmessage = buf.readLine();
// After making the request, I am updating the response to a text view on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
response.setText(getmessage);
}
});
I am unable to write the whole JSON data to the text view. I know that buf.readline returns the response till the end of a line. Right now I am only getting a part of the JSON response, "Not Authenticated:", but I need the whole response.
How do I update the whole JSON response to the text view (response)? If I loop the data using buf.readline in a loop then where can I use it? In which thread?
If there is anything unusual in my code. Please let me know.
I would suggest you to go trough AsyncTask
private class GetDataFromUrl extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
return getmessage;
}
protected void onPostExecute(String result) {
// Result will be available here (this runs on main thread)
// Show result in text view here.
response.setText(result);
}
}
To understand better, as you call AsyncTask, doInBackground runs on the new thread created. Where the network call in placed and data is parsed. Now, we need to access the data on the main thread to update the TextView so override onPostExecute inside AsyncTask that is taking result as a parameter, from doInBackground. Also if you notice..
private class GetDataFromUrl extends AsyncTask<URL, Integer, String>
Here URL is the type we are passing to our AsyncTask for doInBackground
String is what we passing from doInBackground to onPostExecute
and Integer is used to show progress for another method you can override i.e onProgressUpdate .. You can read more in the documentation liked above. Hope it was helpful.
You're only reading the first line of the response with readLine(). Call that in a loop until all lines are read, and append each new line to the previous.
If i understood correcly, you are trying to read all response data line by line. Can you try the following?
#Override
protected String doInBackGround(...){
. . .
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String response = sb.toString();
return response;
}
#Override
protected void onPostExecute(String response){
Textview tv = your_textview;
your_textview.settext(whatever_part_you_get_from_response);
}
Hope this helps.
Try this:
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
EDITED
In your code:
getmessage = buf.readLine();
in variable getmessage reads only first line of JSON. You need to read all lines and concatenate it. How to know did you read all lines or not?
Here is what documentation says about it:
public String readLine()
throws IOException
Returns:
A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached
As you can see, you should invoke this method, save result of it into variable, and check, if variable is not null, then you have read line of JSON. If variable is null, then you have read all JSON into variable and you have completely JSON String.
StringBuilder used to avoid creating unnecessary objects, read more about it here

Android: HttpURLConnection redirect - doInBackground

I'm using HttpURLConnection to do communication with a backend server and im doing so in an async task in the doInBackground method as you should.
Now I need to be able to follow 302 redirects, but I'm having some problems with this. The issue is that the new location usually will be on another host, however when doing the redirect request it seem not to change the URL to a new host hence I get a 404 error saying the specified path does not exits.
Now I know I could set HtppURLConnection.setFollowRedirect but I need to have more control over the redirects so they should not just be followed blindly. The Redirect behavour should be controlled by the object who called the asynctask (when an asynctask object is created you pass the object who creates it in a parameter called _callback).
Heres's my current code:
protected HttpResponse doInBackground(String... req) {
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) this._url.openConnection();
urlConnection.setConnectTimeout( (int) this._timeout*1000);
String body = req[0];
// set headers / write information to output stream if request is post
// create the response object
HttpResponse responseObject = null;
try
{
// get status, contenttype, charset...
InputStream in = null;
if (urlConnection.getResponseCode() != -1 && urlConnection.getResponseCode() < 300)
{
in = new BufferedInputStream(urlConnection.getInputStream(), 8192);
}
else
{
in = new BufferedInputStream(urlConnection.getErrorStream(), 8192);
}
responseObject = new HttpResponse(in, status, contentType, charset);
// if redirect
if (status == 302 && this._callback.onRedirect(responseObject) == true)
{
// recall
String url = urlConnection.getHeaderField("location");
Log.v("Async Task", "Redirect location: " + url);
this._url = null;
this._url = new URL(url);
urlConnection.disconnect();
urlConnection = null;
responseObject = this.doInBackground(req);
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// return the response
return responseObject;
}
// catch some other exceptions
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
} }
}
And as said the problem is that the redirect request seem to change the path of the URL but not the host. The URL object itself seem to contain the right information so I have no idea why this is happening. (I'm getting HTML as response which is an 404 error page that includes the server name of the old server)
Thanks for any help!
Note: HttpResponse is just an object I created for holding the relevant information about the response.
This was caused by the fact that I sent the same headers and did not change the "host" header of the request which caused Apache to be confused it seems.

Categories

Resources