How to Connect Android Device with web serve using AsyncTask - android

I have this asynctask.I need to connect device with web server.Need to send a JSON Arry and receive JSON array. Can i use httpUrlConnection ? or httpClient. Does httpClient support latest versions of Android?
class background_thread extends AsyncTask<JSONArray, Void, Boolean> {
protected Boolean doInBackground(JSONArray... params) {
//connect with server side php script
String UR = "127.0.0.1/abc/index.php";
try {
URL url = new URL(UR);
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
json_array=json_encode();
conn.setDoOutput(true);
conn.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
writeStream(out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return true;
}

You should use google's own volley library to make network calls and handle the response data in model classes. This is the most modular approach. Refer this link for official documentation.

Related

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");

java.io.EOFException on Android Client (API 23) when POSTing Object to Jersey

I want to implement a basic authentication using an Android Client and a Glassfish 4.1.1 Server (communicating through REST-Service).
The Service is working quite well (proven by POSTMAN and another C#-Client) but on Android, it's driven me crazy by now.
It also appears that the object-to-send is received as 'null' on the server side, also an annoying "EOFException" is thrown on the Android Side.
Server side (works fine)
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
public Account validate(Account acc)
{
Account a = null;
a = Database.getInstance().getAccountByUserPw(acc);
return a;
}
Android Client:
public Account postData(String JSONtoSend)
{
URL url;
Account get = new Account();
try {
url = new URL("http://192.xxx.xxx.x:18080/HolidayOutServer/webresources/validateacc");
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestMethod("POST");
urlCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlCon.setRequestProperty("Accept", "application/json; charset=UTF-8");
urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
OutputStreamWriter out = new OutputStreamWriter(urlCon.getOutputStream());
out.write(JSONtoSend);
ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
get = (Account) ois.readObject();
return get;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return get;
}
which is called within this:
class help extends AsyncTask<String, Void, Account>
{
#Override
protected Account doInBackground(String... params) {
return postData(new Gson().toJson(new Account("aleqs", "lexx", -2)));
}
}
Problems in a nutshell:
Jersey Server receives null
Android throws this ridiculous EOFException.
Can somebody help ?
Thanks in advance,
John.
Ok, I managed to find a solution here after hours.
This code works for me:
try( DataOutputStream wr = new DataOutputStream( urlCon.getOutputStream())) {
wr.write(new Gson().toJson(new Account("aleqs", "lexx", -2)).getBytes());
}
Reader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
response = sb.toString();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return response;
Change the return type of "donInBackGround" to String and let the helper class extend -String, Void, String-.
MOST IMPORTANT: CHECK IF YOUR ATTRIBUTES ON CLIENT SIDE (eg. id, name, ..) match with those from SERVER SIDE.
Consider cap locks and so on..
Cheers !

Accessing REST API in Android Using Request Headers

I have a question about the proper syntax and order of code in regards to accessing a REST API.
I am trying to access a database that I made on an mBaas called backendless.com. (The following data information is specific to this mBaas but my question is more about the general process of accessing REST API's in Android)
According to their tutorial to bulk delete (https://backendless.com/documentation/data/rest/data_deleting_data_objects.htm) I need a URL that queries my database for a specific value and then deletes it. I have that value. They also need 3 request headers (application-id, secret key, application type).I have those as well.
I utilized all of this information in an ASyncTask class that technically should open the url, set the request headers, and make the call to the REST API. My only issue is, I have no idea if I'm missing some kind of code here? Is my current code in proper order? Every time my class is executed, nothing happens.
I also get a log cat exception in regards to my URL: java.io.FileNotFoundException: api.backendless.com/v1/data/bulk/...
The URL does not lead to anything when I place it in my browser but I'm told that it shouldn't since the browser sends it as a GET request.
Anyway, here is my ASyncTask Class with all of the info. Does anyone know if this code looks correct or am I missing something here? I'm new to making these type of calls and don't really understand the roll that request-headers play in accessing REST APIs. Please let me know. Thank you!
class DeleteBulkFromBackEnd extends AsyncTask<Void,Void,String>{
final String API_URL = "https://api.backendless.com/v1/data/bulk/LocalPhoneNum?where%3DuserEmailID%3Dmark#gmail.com";
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(API_URL);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty( "application-id","12345678" );
urlConnection.setRequestProperty( "secret-key","12345678" );
urlConnection.setRequestProperty( "application-type", "REST" );
urlConnection.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("Contact","ERROR " + e.toString() );//IO Exception Prints in log cat not recognizing URL
e.printStackTrace();
}finally {
urlConnection.disconnect();
}
return null;
}
}
I recommend you to use okhttp for easy network access.
And check the response code and response body.
In your build.gradle:
compile 'com.squareup.okhttp3:okhttp:3.4.1'
Your AsyncTask will be like this:
class DeleteBulkFromBackEnd extends AsyncTask<Void, Void, String> {
final String API_URL = "https://api.backendless.com/v1/data/bulk/LocalPhoneNum?where%3DuserEmailID%3Dmark#gmail.com";
final OkHttpClient mClient;
public DeleteBulkFromBackEnd(OkHttpClient client) {
mClient = client;
}
#Override
protected String doInBackground(Void... params) {
try {
Request request = new Request.Builder()
.url(API_URL)
.delete()
.header("application-id", "12345678")
.header("secret-key", "12345678")
.header("application-type", "REST")
.build();
Response response = mClient.newCall(request).execute();
Log.d("DeleteBulkFromBackEnd", "Code: " + response.code());
Log.d("DeleteBulkFromBackEnd", "Body: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Execute the AsyncTask like this:
OkHttpClient client = new OkHttpClient();
void someMethod() {
...
new DeleteBulkFromBackEnd(client).execute();
...
}
As I've commented, here's the solution:
class DeleteBulkFromBackEnd extends AsyncTask<Void,Void,String>{
final String API_URL = "https://api.backendless.com/v1/data/bulk/LocalPhoneNum?where%3DuserEmailID%3Dmark#gmail.com";
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(API_URL);
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty( "application-id","12345678" );
urlConnection.setRequestProperty( "secret-key","12345678" );
urlConnection.setRequestProperty( "application-type", "REST" );
urlConnection.setRequestMethod("DELETE");
urlConnection.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("Contact","ERROR " + e.toString() );//IO Exception Prints in log cat not recognizing URL
e.printStackTrace();
}finally {
urlConnection.disconnect();
}
return null;
}
}

Android HttpUrlConnection response object

Hey i'm using HttpUrlConnection in my app. And it's seems to me that every time when I'm making call as .getInputStream() or urlConnection.getResponseCode() etc it makes another request, so it is not good for me, when i'm making POST request. Is there a way to get some kind of response object which encapsulates response data and can be accessible from UI thread, something like this:
private class RegisterAsync extends AsyncTask<String, Void, HttpResponse> {
protected String doInBackground(String... strings) {
HttpURLConnection urlConnection = null;
String message = null;
try {
URL url = new URL(REGISTER_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(strings[0].getBytes("UTF-8"));
out.flush();
out.close();
HttpResponse response = urlConnection.getResponse();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return Response;
}
protected void onPostExecute(HttpResponse response) {
//Do some with response object: get status, headers, content etc?
}
}
you can do the following steps:
Create the webservice call in a singleton class
Parse the response and encapsulate it in a custom object(made by you) and save the parsed object into the singleton as instance object.
After this, you can simply send a broadcast message to your activity to let it know that the parsed data is available in the singleton
the onReceive() method of BroadcastReceiver runs on UI thread so you can quickly update your UI there..
After you implement that you can simply call the singleton webservice call method from your activity right after you register to the intent that will be sent from the singleton...

Android interacting with php

I have a problem! I have a connection with a php page to connect with database and the method works fine on Froyo, but doesn't work on newer versions of Android. What is the problem?
public static String interact(String request){
String result="test";
String site = "http://xxxx.net:nnn/xxx";
URL url = new URL(site);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(request);
wr.flush();
wr.close();
Scanner in = new Scanner(connection.getInputStream());
while(in.hasNextLine())
result+=in.nextLine();
connection.disconnect();
return result;
}
catch (UnknownHostException e) {
return e.getMessage();
} catch (IOException ex) {
return ex.getMessage();
}
catch (Exception ex){
return ex.getMessage();
}
}
I need to send data and get response, but it just gives me null on newer Android than 2.2.
you are running Network Request on main thread.
Android >=3.0 does not alow this. you need to use AsyncTask to call Network Request
Yes this is not allowed on version lower than 3.0. however you can override the rules by doing some setting bypass but at the very least don't do that as it might give app-crash to you.
I suggest to raise the level of your min-SDK level.

Categories

Resources