I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. I like to understand how I send an information to a web service.
I try to update the post but i got some mistake.. I know my code has some mistake My code is:
enter code here
package com.example.paulo.myapp.POST;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paulo.myapp.R;
import com.facebook.internal.BundleJSONConverter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Post_Dados extends AppCompatActivity implements View.OnClickListener {
TextView isconected;
EditText customer, pais, twitter;
Button btn_enviar;
String person, country, tw;
static Dados dados;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post__dados);
/* recupera as views */
isconected = (TextView) findViewById(R.id.conected);
customer = (EditText) findViewById(R.id.customer);
pais = (EditText) findViewById(R.id.pais);
twitter = (EditText) findViewById(R.id.twitter);
btn_enviar = (Button) findViewById(R.id.sendWS);
/* checa se está conectado */
if (isConnected()) {
isconected.setText("Conectado !!!!");
}
else {
isconected.setText("Não conectado!!!");
}
/* click do botão */
btn_enviar.setOnClickListener(this);
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager ) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if ( info != null && info.isConnected()){
return true;
}
else { return false; } }
#Override
public void onClick(View view) {
String c = customer.getText().toString();
String p = pais.getText().toString();
String t = twitter.getText().toString();
if ( c.equals("") || p.equals("") || t.equals("") )
{
Toast.makeText(getBaseContext(), "Preenche os campos os dados!", Toast.LENGTH_LONG).show();
}
else{
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}
}
/*metodo de conexao */
private static String POST(String url, String person) throws IOException, JSONException {
InputStream inputStream = null;
String result = "";
try{
/* 1. cria o httpClient */
URL endWeb = new URL(url);
HttpURLConnection con = (HttpURLConnection) endWeb.openConnection();
// 2. configurando o POST
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setRequestProperty("Accept", "application/json");
//3. define enviar e receber
con.setDoOutput(true);
con.setDoInput(true);
//4.faz a conexao
con.connect();
//5. Objeto json
String json = " ";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name",dados.getNome());
jsonObject.accumulate("country", dados.getEmail());
jsonObject.accumulate("twitter", dados.getTwitter());
//6.connverte json to json string
json = jsonObject.toString();
// Escreve o objeto JSON usando o OutputStream da requisição:
OutputStream outputStream = con.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
}
catch (Exception e){
throw e;
}
return "ok";
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>{
String result;
#Override
protected String doInBackground(String... urls) {
dados = new Dados(person.toString(), country.toString(), tw.toString());
try {
result = POST(urls[0], person);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Dados enviados!", Toast.LENGTH_LONG).show();
}
}
}
I this url http://hmkcode.appspot.com/post-json/index.html is to check it´s ok.
I like a help to get it ok.
Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. Fortunately retrofit is awesome and is very widely used. There are a lot tutorials for it, you might try this one for example.
Related
I am trying to write a network functionality for an android application with android studio.
It is very simple. I just try to post some data to an url and fetch data back (all in simple HTTP).
I am testing with the emulator, device is Pixel 2 API 28.
As long as the internet is activated on the emulator everything works fine.
But as soon as i disable the wifi, the application hangs when I try to send the data, and finally crashes. Android offers to stop the application.
It hangs on this call:
urlConnection.getOutputStream().write(postDataBytes);
Documentation and web say, that this method should throw an exception, when there is no internet connection. Especially the UnknownHostException is mentioned very often. But I do not receive any exception.
Where could I go from here?
Here is the code of the whole connection class i use. The doInBackground method is the place where the internet magic happens and the error occures:
package com.example.tf2;
//This class is used for easier networking.
//It is using volley..
import android.content.Context;
/* import android.graphics.Bitmap; */
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/* Info about "associative arrays" for the post params taken from Stackoverflow:
https://stackoverflow.com/questions/5122913/java-associative-array
*/
public class mvNetConnect extends AsyncTask<String, Void, String> {
private final String endpoint = "*** here is a valid url ***";
Map<String, String> post_params = new HashMap<String, String>();
String mode = "GET";
String token = "";
private Context useContext;
public mvNetConnect(Context myContext) {
useContext = myContext;
}
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection;
try {
//Daten aus Eingabefeldern auslesen.
//TextView textview_username =
url = new URL(endpoint + urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(1000); // Timeout in Millisekunden. Ansonsten bekommt der Enduser nie eine Antwort..
urlConnection.setReadTimeout(1000);
//Falls wir ein Token haben, fügen wir es dem Request hinzu..
if(token != "") {
urlConnection.addRequestProperty("auth", token);
}
//Falls dies ein Post-Aufruf ist, machen wir auch einen daraus..
StringBuilder postData = new StringBuilder();
if(mode == "POST") {
urlConnection.setRequestMethod("POST");
//Post Parameter hinzufügen (Loop taken from stackoverflow (Thread from harto): https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap)
for (Map.Entry<String, String> entry : post_params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// Add Params to request..
if (postData.length() != 0) {
postData.append('&');
}
postData.append(URLEncoder.encode(key, "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(value, "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
urlConnection.setDoOutput(true);
urlConnection.getOutputStream().write(postDataBytes);
}
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read(); //Erstes Zeichen lesen.
while(data != -1) { //So lang es Daten gibt.
char current = (char) data; //Zeichen umwandeln.
result += current; //Zeichen an Ausgabe anhängen.
data = reader.read(); //Nächstes Zeichen lesen.
}
} catch(UnknownHostException e) {
Log.i("Info", "error!!!");
} catch(MalformedURLException e) {
Log.i("Info", "no error?");
e.printStackTrace();
return "Failed";
} catch(Exception e) {
Log.i("Info", "errors..");
e.printStackTrace();
return "Failed";
} catch (Throwable throwable) {
// Output unexpected Throwables.
Log.i("info", throwable.toString());
}
Log.i("Info", result.toString());
return result;
}
public void setModeToPost() {
mode = "POST";
}
public void setModeToGet() {
mode = "GET";
}
public void setToken(String _token) {
token = _token;
}
public void addPostParam(String key, String value) {
post_params.put(key, value);
//To extract a key one could use: post_params.get(key);
}
public void clearPostParams(String key, String value) {
post_params.clear();
}
}
I found this old android example code that can filter tweets from Twitter's live streaming API according to the input of user, but the problem is that it uses the basic authorization.
Obviously it wouldn't work and I got the "401 unauthorized" error.
Here is the original code:
package com.teleknesis.android.twitter.livestream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class TwitterLiveStreamingActivity extends Activity {
private List<HashMap<String,String>> mTweets = new ArrayList<HashMap<String,String>>();
private SimpleAdapter mAdapter;
private boolean mKeepRunning = false;
private String mSearchTerm = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAdapter = new SimpleAdapter(this, mTweets, android.R.layout.simple_list_item_2, new String[] {"Tweet", "From"}, new int[] {android.R.id.text1, android.R.id.text2});
((ListView)findViewById(R.id.Tweets)).setAdapter(mAdapter);
}
public void startStop( View v ) {
if( ((Button)v).getText().equals("Start") ) {
mSearchTerm = ((EditText)findViewById(R.id.SearchText)).getText().toString();
if( mSearchTerm.length() > 0 ) {
new StreamTask().execute();
mKeepRunning = true;
((Button)v).setText("Stop");
}
else {
Toast.makeText(this, "You must fill in a search term", Toast.LENGTH_SHORT).show();
}
}
else {
mKeepRunning = false;
((Button)v).setText("Start");
}
}
private class StreamTask extends AsyncTask<Integer, Integer, Integer> {
private String mUrl = "https://stream.twitter.com/1/statuses/filter.json?track=";
#Override
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}
catch (Exception e) {
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
private void parseTweets( BufferedReader reader ) {
try {
String line = "";
do {
line = reader.readLine();
Log.d("Twitter", "Keep Running: " + mKeepRunning
+ " Line: " + line);
JSONObject tweet = new JSONObject(line);
HashMap<String, String> tweetMap = new HashMap<String, String>();
if (tweet.has("text")) {
tweetMap.put("Tweet", tweet.getString("text"));
tweetMap.put("From", tweet.getJSONObject("user")
.getString("screen_name"));
mTweets.add(0, tweetMap);
if (mTweets.size() > 10) {
mTweets.remove(mTweets.size() - 1);
}
//mAdapter.notifyDataSetChanged();
publishProgress(1);
}
} while (mKeepRunning && line.length() > 0);
}
catch (Exception e) {
// TODO: handle exception
}
}
protected void onProgressUpdate(Integer... progress) {
mAdapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Integer i) {
}
}
}
I try to replace the credential with the OAuth:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true);
cb.setOAuthConsumerKey("*************");
cb.setOAuthConsumerSecret("*************");
cb.setOAuthAccessToken("*************");
cb.setOAuthAccessTokenSecret("*************");
Didn't work..(I have all the correct keys and secrets)
I also tried to insert this whole part into one currently operational twitter client(I can get all the tweets on timeline and all), I don't know if I did it right but it didn't work either. Also in this case, if the Oauth was done again in this code and it worked, does that mean when I run the application I have to be redirected to the authorization page twice if I wanted to use this filter function? I would love a fix that the twitter feed can be used by both the timeline and this filtering mode.
Would anybody shed some lights on how I can do this?
Problem solved.
Here is the modified code:
protected Integer doInBackground(Integer... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
CONSUMER_SECRET);
consumer.setTokenWithSecret(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
HttpGet request = new HttpGet();
request.setURI(new URI("https://stream.twitter.com/1/statuses/filter.json?track=" + mSearchTerm));
consumer.sign(request);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
parseTweets(reader);
in.close();
}
I'm trying to connect to a servlet in localhost from my Android Emulator.
I created a project in Eclipse named SimpleHttpGetRequest with an activity named "HttpGetServletActivity".
I created in NetBeans a project named "HttpGetRequest" containing a servlet.
The code in my "HttpGetServletActivity" activity is :
package com.mobdev.simplehttprequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/HttpGetRequest/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[]{ URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("get");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
The source code of my servlet is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
I deployed my servlet in Apache server (i'm using xampp);
I added permission for network connection
When I run my App and click on the button, the App crashes, and I don't know why !!
Can anybody help me, please ? Im' stuck.
I tried :
Wifi connection : I did run my App on a real device, instead of "10.0.2.2" I put the ip adress of my PC but it doesn't work ;
Access to project HttpGetrequest from Android Emulator browser, it worked ;
i have an android program having two fields name and pas which post the data in json format and the response is "data sent." instead of that response i want the name and pass parameters to be checked by my api which is connected to database.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data sent!", Toast.LENGTH_LONG).show();
}
the complete code
package com.hmkcode.android;
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);
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("Email", person.getName());
jsonObject.accumulate("Password", person.getCountry());
// 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://dev.blinkawards.com/blinkawards.RestService/Service1/LoginRequestTemp");
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());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, 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
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;
}
}
I have an android login app which post two parameters i.e username and password. These 2 parameters are passed as json. The problem is I m not able to call the .net web api. This api confirms the login details and response I get from the page is id = 0 message "null"
I dont know where i am going wrong.
The complete source code
package com.hmkcode.android;
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);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are connected");
}
else{
tvIsConnected.setText("You are NOT connected");
}
// 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 login = new JSONObject();
login.accumulate("Email", person.getName());
login.accumulate("Password", person.getCountry());
// 4. convert JSONObject to JSON to String
json = login.toString();
JSONObject finaldata = new JSONObject();
finaldata.put("LoginRequestTemp", json);
// ** 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://dev.blinkawards.com/blinkawards.RestService/Service1/LoginTemp");
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());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(),result , 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
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;
}
}