How to Send a Data to a Web Server from Android

How to send a data to a web server from Android

You can make GET or POST requests using AndroidHttpClient:

  1. Create an AndroidHttpClient to execute your requests.
  2. Create either an HttpGet or HttpPost request.
  3. Use setEntity and setHeader methods to populate the request.
  4. Use one of the execute methods on your client with your request.

This answer seems like a fairly complete code sample.

Send data from a web server to an android app

There is two best approach you can follow.

  1. from server to app: in this case make corn job(timer service) which send push notification to android app. when app get push notification create one background service which download any data from server.

Note: if you have small text with limit of 100 char then no need to create service just send using push notification


  1. fetch data from server: in this case make one background service(auto start service) in android app. which run within some interval period like 1 hour or more(whatever your requirement). that service fetch data from server.(in this case android app eat battery of user device because of background service)

i will suggest you to use 1st approach because its easy and best way(in case of performance) your server do everything & android app have to just receive data.


how to implement push notification best tutorial using PHP & android(its old but just read official docs)

Android App sending data to a web server

Take a look into SyncAdapter it allows the framework to optimize data transfers to preserve device's battery life.

The sync adapter component in your app encapsulates the code for the
tasks that transfer data between the device and a server. Based on the
scheduling and triggers you provide in your app, the sync adapter
framework runs the code in the sync adapter component.

http://developer.android.com/training/sync-adapters/creating-sync-adapter.html

How to send data to Server

You can use OkHttp to achieve this easily. In order to include the library use the following in dependencies:
compile 'com.squareup.okhttp3:okhttp:3.2.0'

As a sample you can use it like this:

RequestBody formBody = new FormBody.Builder()
.add("username", USER_NAME)
.add("password", PASSWORD)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
OkHttpClient client = new OkHttpClient();

Response response = client.newCall(request).execute();
if(response.code == 200){
String responseData = responses.body().string();
//Process the response Data
}else{
//Server problem
}

Best way to send and receive data(POST and GET) from Android to web server using Java?

For Android there's some alternatives for send HTTP Rest Request from your App but the most simple and easy to configure is Retrofit, this library allows to call to your Rest API from your Android App and you can Attach multiple configurations for Logging, Messaging, etc. Another library that you can use is RxJava

Android, send string from app to web server

try below code :-

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;

public class MainActivity extends Activity implements OnClickListener {

TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;

Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);

// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}

// add click listener to Button "POST"
btnPost.setOnClickListener(this);

}

public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {

// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();

// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);

String json = "";

// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());

// 4. convert JSONObject to JSON to String
json = jsonObject.toString();

// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);

// 5. set json to StringEntity
StringEntity se = new StringEntity(json);

// 6. set httpPost Entity
httpPost.setEntity(se);

// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);

// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";

} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}

// 11. return result
return result;
}

public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
@Override
public void onClick(View view) {

switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}

}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {

person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());

return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}

private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;

inputStream.close();
return result;

}
}

see below link for more info :-

http://hmkcode.com/android-send-json-data-to-server/

http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89

How to post data to my web server using mobile SMS without internet?

I found a solution to my problem. The internet connectivity problem can be solved in the following way.

When internet is not available on your user's device, send an SMS which contains location coordinates and user name to a second mobile device in which internet is available. Then that second device will parse the incoming SMS, extract coordinates and username and will send it to the server.



Related Topics



Leave a reply



Submit