In most of the android applications it is essential that app may need to connect to internet and make some HTTP requests. In this article i’ll be demonstrating about making simple HTTP Requests in android.

Below are the code snippets to handle HTTP requests.

Download Code

Creating HTTP Client and HTTP Post

// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();

// Creating HTTP Post
HttpPost httpPost = new HttpPost("http://www.example.com/login");

 

Bulding Post Parameters

The following code will create post parameters pair with key and value.

// Building post parameters, key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
nameValuePair.add(new BasicNameValuePair("password", "encrypted_password"));

 

URL Encoding POST data

Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.

// Url Encoding the POST parameters
try {
	httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
	// writing error to Log
	e.printStackTrace();
}

 

Finally making HTTP Request

Finally you need to execute httpPost using the httpClient created before.

// Making HTTP Request
try {
	HttpResponse response = httpClient.execute(httpPost);

	// writing response to log
	Log.d("Http Response:", response.toString());

} catch (ClientProtocolException e) {
	// writing exception to log
	e.printStackTrace();
		
} catch (IOException e) {
	// writing exception to log
	e.printStackTrace();
}

 

Final Code

The following is the final code to make http Requests. I am writing response to log. Check your Log report in Eclipse to see your http response.

package com.androidhive.httprequests;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class AndroidHTTPRequestsActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Creating HTTP client
		HttpClient httpClient = new DefaultHttpClient();
		// Creating HTTP Post
		HttpPost httpPost = new HttpPost(
				"http://www.example.com/login");

		// Building post parameters
		// key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
		nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
		nameValuePair.add(new BasicNameValuePair("message",
				"Hi, trying Android HTTP post!"));

		// Url Encoding the POST parameters
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		} catch (UnsupportedEncodingException e) {
			// writing error to Log
			e.printStackTrace();
		}

		// Making HTTP Request
		try {
			HttpResponse response = httpClient.execute(httpPost);

			// writing response to log
			Log.d("Http Response:", response.toString());
		} catch (ClientProtocolException e) {
			// writing exception to log
			e.printStackTrace();
		} catch (IOException e) {
			// writing exception to log
			e.printStackTrace();

		}
	}
}
Subscribe
Notify of
guest
138 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] is combination of some of my previous tutorials. I hope you covered these tutorials before. Android making HTTP Requests Android JSON Parsing Tutorial Android SQLite Database Tutorial Android Login and Registration […]

Akhilesh Saini
7 years ago

what is the procedure to access the “remote database of website” please help….

KGPrakash
KGPrakash
7 years ago

Hi Ravi,

How may I connect with username and password to my website’s login…?

jejeje
jejeje
7 years ago

your motherfucker, HIJO DE PUTA

vishal
vishal
7 years ago

fack comment……………………

dinosaurclover
dinosaurclover
7 years ago

This is not a tutrial, It’s an example.

jammin58
jammin58
7 years ago
Reply to  dinosaurclover

While I appreciate “tutorial” posting I absolutely agree with dinosaurclover that this is more of an “example” than true tutorial.

Younes
Younes
7 years ago

Add this if not working:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

.permitAll().build();

StrictMode.setThreadPolicy(policy);

goonerdroid
goonerdroid
7 years ago

Guys can i pass a String array in the Basic name value pair..if not then can you suggest some alternatives….help!!

flavio
flavio
6 years ago

I downloaded your project and runs normal, but in my otros projects where the error on the line:

HttpResponse response = httpClient.execute (HttpPost);

sdvipeen
sdvipeen
6 years ago

wats the output of this example.?

Abu Zahed Jony
Abu Zahed Jony
6 years ago

Thanks for the post. I am trying to post a string array.
My code:
for(String attachment : attachments){
multipartEntity.addPart(“attachments[]”, new StringBody(attachment));
}
It is not working for me. server received full array as string( example “[“a”, “b”]” ). but I have to pas only string array (example- [“a”,”b”] ). Please help.

Sanny Singhs
Sanny Singhs
6 years ago

It’s very helpful. May know how to do the PUT and DELETE methods though

MM
MM
6 years ago

Hello Ravi. I’m trying to download the source code, but when I subscribe my e-mail I NEVER receive the confirmation in my e-mail, I already verify my spam box and tried another e-mail.

Ravi Tamada
6 years ago
Reply to  MM

Please check your SPAM folder.

MM
MM
6 years ago
Reply to  Ravi Tamada

As I said before, I’ve checked the spam folder from my two emails. =/

Ravi Tamada
6 years ago
Reply to  MM

Ok. If you have Gmail account please try with that email id.

MM
MM
6 years ago
Reply to  Ravi Tamada

Works perfectly! I downloaded and all is working, but I can’t download this: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ maybe the link is broken.
Thanks Ravi.

Ravi Tamada
6 years ago
Reply to  MM

Please check your SPAM folder for activation email.

A way from Away
A way from Away
6 years ago

can we do it for local server in our machine

Rafique Mohammed
Rafique Mohammed
6 years ago

You are executing it on UIThread. Wont it throw exception and crash the APP?

Ndungu Njenga
Ndungu Njenga
6 years ago

where do i download this library?

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

Rendy
Rendy
6 years ago

hello
I found tutorial about httpclient and I have proble with httpost
how to post with url parameter

http://domain.com/api/cost?key=7867t6756&destination=89&weight=1000&origin=176
this is what i want post to url >>
key=7867t6756&destination=89&weight=1000&origin=176this my code:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

if (method == POST) {
HttpPost httpPost = new HttpPost(“http://domain.com/api/cost”);

if (params != null) {

httpPost.setHeader(“Accept”, “application/x-www-form-urlencoded”);
httpPost.setHeader(“Content-type”, “application/x-www-form-urlencoded”);
httpPost.setHeader(“Referer”, “key=7867t6756&destination=89&weight=1000&origin=176”);
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);

Thank you

Ravi Tamada
6 years ago
Reply to  Rendy

Try making requests with volley library. Its very easy and fastest way of making http requests.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

Guest
Guest
6 years ago
Reply to  Ravi Tamada

thank you
i hope find the solution

Rendy
Rendy
6 years ago
Reply to  Ravi Tamada

Thank you
I hope found the solution

mani
mani
6 years ago
Reply to  Ravi Tamada

how can play number of videos from my phone

Saad
Saad
5 years ago

hello sir know i create an apps which is used to login for my site in device when i testing in bluestack
it work means it send the user id and password to particualar URL when i install that apps in my real device it open when i click submit button it show unfortunatly your apps has been stopped i tried in any other device but it show same problem please help how to resolved this problem .

MajorTom8461
MajorTom8461
5 years ago

I had this working for my localhost (wamp server), I could hit my database via a php page. Now I have hostgator and I cannot reach my php page with my URL. Does any one know how to fix this?

– No errors its like its just not hitting the server.

HttpPost httpPost = new HttpPost(“http://mydomain/login4.php”);

prince raizadha
prince raizadha
5 years ago

my lord thanks a lot
i add some in this if it cause error of sticky in higher version than put this code before set layout

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

prasad
prasad
5 years ago

Your tutorials are the most easy to understand tutorials in this planet. I learnt many concepts here. I want you to explain about what are web services, Different types of web services, methods used, creating a web service in java, how a web service receives request (HTTP, SOAP,REST etc. Not even one of them is understood by me), difference between a web service and servlet, how to create Database, save data in database via servelet/web service/ android application. Sorry as the list is too long. But I really liked the way you explain, and can easily understand. By the way I too live in Hyderabad

Ravi Tamada
5 years ago
Reply to  prasad

Thanks Prasad. Happy Coding 🙂

Hakan KANMAZ
Hakan KANMAZ
5 years ago

how can i post my data?
{ “OrgID”:”1″,
“UserDepartment”:”1″,
“WorkType”:”1977″,
“WorkDefinition”:”EXAMPLE_EXAMPLE”,
“Confirmed”:[
{“Confirmed”:”qaAgo/+/j/XhECIhlAo2SQ==,}
{“Confirmed”:”qaAgo/+/j/XhECIhlAo2SQ==”}],
“FileName”:””,
“FileMimeType”:””,
“FileContent”:””
}
i write this codes but i couldn’t post
public static void sendParameter(String organizationId, String departmentId, String workType, List comfirmedList, String fileName, String fileMimeType, String fileContent, String definition) {

parameterList = new ArrayList();
parameterList.add(new BasicNameValuePair(“OrgID”, organizationId));
parameterList.add(new BasicNameValuePair(“UserDepartment”, departmentId));
parameterList.add(new BasicNameValuePair(“WorkType”, workType));
parameterList.add(new BasicNameValuePair(“Confirmed”, String.valueOf(comfirmedList)));
parameterList.add(new BasicNameValuePair(“FileName”, fileName));
parameterList.add(new BasicNameValuePair(“FileMimeType”, fileMimeType));
parameterList.add(new BasicNameValuePair(“FileContent”, fileContent));
parameterList.add(new BasicNameValuePair(“WorkDefinition”, definition));
}

Nilesh
Nilesh
5 years ago

Thanks for put this tutorial.
but HttpClient is not working in my project for that what can i do?
Is there any library which put in gradle.build ? or package or Build Tools which i not installed ?
Thanks in advance.

Ravi Tamada
5 years ago
Reply to  Nilesh

Please follow this tutorial. You can use String Request mentioned in this article to make a http request.

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

hamad
hamad
5 years ago

Can we add progress update with this code , please email me on

hamad.kicsit@gmail.com

surya Mouly
surya Mouly
5 years ago

sir , i want to post data to server in json format using the same service handler class you have used in json parsing tutorial.. and i am getting trouble with this parameter List params can you plz help me out

Amitesh Banerjee
Amitesh Banerjee
5 years ago

Your tutorials are the best and easiest to understand.. however as httpclient is now depricated in latest android builds can you help me with this particular piece of code? I’ve tried a lot to convert this into httpurlconnection it simply doesnt work for me…

HttpClient httpClient = new DefaultHttpClient();

// Creating HTTP Post

HttpPost httpPost = new HttpPost(link);

//Name value pair created what you want to send to server

List nameValuePair = new ArrayList(2);

nameValuePair.add(new BasicNameValuePair(“Languages”,lang));

nameValuePair.add(new BasicNameValuePair(“voice”,vc));

nameValuePair.add(new BasicNameValuePair(“ex”,”execute”));

nameValuePair.add(new BasicNameValuePair(“op”,text));

nameValuePair.add(new BasicNameValuePair(“count”,count));

nameValuePair.add(new BasicNameValuePair(“speed”,speed));

//httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, “UTF-8”)); // UTF 8 added to send indic string to server

HttpResponse httpResponse = httpClient.execute(httpPost);

final int statusCode = httpResponse.getStatusLine().getStatusCode();

Log.d(“Response Status Code”,String.valueOf(statusCode));

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClientProtocolException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

and this is what i have coded for the httpurlconnection:

URL url = new URL(link);

urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setRequestMethod(“POST”);

Map param = new LinkedHashMap();
param.put(“Languages”, lang);

param.put(“voice”,vc);
param.put(“ex”,”execute”);

param.put(“op”,nt);
param.put(“count”,count);
param.put(“speed”,speed);

StringBuilder postData = new StringBuilder();
for (Map.Entry param1 : param .entrySet()) {
if (postData.length() != 0) postData.append(‘&’);
postData.append(URLEncoder.encode(param1.getKey(), “UTF-8”));
postData.append(‘=’);
postData.append(URLEncoder.encode(String.valueOf(param1.getValue()), “UTF-8”));
}
byte[] postDataBytes = postData.toString().getBytes(“UTF-8”);
int postDataLength = postDataBytes.length;

urlConnection.setRequestProperty( “charset”, “utf-8”);
urlConnection.setRequestProperty( “Content-Length”, Integer.toString( postDataLength ));
urlConnection.setUseCaches(false);
urlConnection.getOutputStream().write(postDataBytes);
Log.d(“getoutputstream”, postDataBytes.toString());

InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// readStream(in);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
str = br.readLine();

Log.d(“output of str”,str);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}

Please tell me what I am doing wrong?

Swati Gupta
Swati Gupta
5 years ago

can you write android-making-http-requests using httpurlconnection ?

Vinita
Vinita
4 years ago

I am trying to add header :

httpPost.setHeader(“deviceid”, “358978060711939”);
httpPost.setHeader(“token”, “eyJ0eXOTI0ODkyM30.PAuNrDee1vi74”);

but I am getting error:
Authentication error: Unable to respond to any of these challenges.

How can I add header?

Aman Rai
Aman Rai
4 years ago

Thnks for Tutorial.
but i want to send Object in Name Value Pairs.. how i can send..
ex.
nameValuePair.add(new BasicNameValuePair(“email”, “user@gmail.com”));
bt i want
Inform infrm= new Inform;
nameValuePair.add(new BasicNameValuePair(“inform”, inform));
can i send Object Refernce like this. plz sir help me

K S UMA SANKAR
K S UMA SANKAR
4 years ago

I am trying for a HttpRequest

I used the following program to import the class files

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

I am getting cannot resolve HttpClient

Nasir Mushtaq
Nasir Mushtaq
4 years ago

i want to get the response and convert that into pdf file how can i do tha….my server actually creates pdf file of the data which i am sending throught post method using fpdf library .

‫עידן בן שמעון‬‎
‫עידן בן שמעון‬‎
4 years ago

Or you can just use this awesome library

https://github.com/studioidan/HttpAgent

Geraldo K Fillipus
Geraldo K Fillipus
4 years ago

Hi Ravi good tutorial

I have an API developed in nodeJS, Express and Mongodb that i want to connect to my android, so can i use Apache to do the transaction between my API?

Thankx

deepti
deepti
4 years ago

next time please do mention which all jars to be added. I am facing so many errors and still google-ling to fix them 🙁

rahul patel
rahul patel
3 years ago

hie sir i want to post data on json for that i need to append my url with id but its not working can u help me . plz show any exmple of appending url.

shiben
shiben
3 years ago

Hi,

I want to consume a RST API for instance.service-now.com

Below is the code that i have

package com.example.android.checkapi;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends AppCompatActivity {

// Progress Dialog Object
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView)findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText)findViewById(R.id.loginEmail);
// Find Password Edit View control by ID
pwdET = (EditText)findViewById(R.id.loginPassword);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage(“Please wait…”);
// Set Cancelable as False
prgDialog.setCancelable(false);
}

/**
* Method gets triggered when Login button is clicked
*
* @param view
*/

public void loginMain(View view){

// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// Instantiate Http Request Param Object
RequestParams params = new RequestParams();
// When Email Edit View and Password Edit View have values other than Null
/**if(Utility.isNotNull(email) && Utility.isNotNull(password)){
// When Email entered is Valid
if(Utility.validate(email)){*/
// Put Http parameter username with value of Email Edit View control
params.put(“username”, email);
// Put Http parameter password with value of Password Edit Value control
params.put(“password”, password);
// Invoke RESTful Web Service with Http parameters
invokeWS(params);
//}
}

/**
* Method that performs RESTful webservice invocations
*
* @param params
*/

public void invokeWS(RequestParams params){
// Show Progress Dialog
prgDialog.show();
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get(”

https://instance.service-now.com/api/now/table/problem?sysparm_limit=1

“,params ,new AsyncHttpResponseHandler() {

public void onSuccess(int status_code, Header[] headers, byte[] responseBody) {

// Hide Progress Dialog
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(String.valueOf(responseBody));
// When the JSON response has status boolean value assigned with true
if (obj.get(“status_code”).equals(“200”)){
Toast.makeText(getApplicationContext(), “You are successfully logged in!”, Toast.LENGTH_LONG).show();
// Navigate to Home screen
navigatetoHomeActivity();
}
// Else display error message
else{
errorMsg.setText(obj.getString(“error_msg”));
Toast.makeText(getApplicationContext(), obj.getString(“error_msg”), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), “Error Occured [Server’s JSON response might be invalid]!”, Toast.LENGTH_LONG).show();
e.printStackTrace();

}
}
// When the response returned by REST has Http response code other than ‘200’
@Override
public void onFailure(int status_code, Header[] headers, byte[] responseBody, Throwable error) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is ‘404’
if(status_code == 404){
Toast.makeText(getApplicationContext(), “Requested resource not found”, Toast.LENGTH_LONG).show();
}
// When Http response code is ‘500’
else if(status_code == 500){
Toast.makeText(getApplicationContext(), “Something went wrong at server end”, Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else{
Toast.makeText(getApplicationContext(), “Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]”, Toast.LENGTH_LONG).show();
}
}
});

}
/**
* Method which navigates from Login Activity to Home Activity
*/
public void navigatetoHomeActivity(){
Intent homeIntent = new Intent(getApplicationContext(),HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
}

I get the error : Unexpected Error occcured! [Most common Error: Device might not be
connected to Internet or remote server is not up and running]”

I have used the below in manifest file

What could i be doing wrong ?

Please help

Nick Patel
Nick Patel
2 years ago

Using HttpPost and NameValuePair is deprecated. So what should we use now?

Nick Patel
Nick Patel
2 years ago
Reply to  Ravi Tamada

Is it possible to post data on a localhost using HttpUrlConnection and OutputStreamWriter?

moczul
moczul
9 years ago

Hi,

Great post, are you planning to write sth about xml/json parsing ?

Ravi Tamada
9 years ago
Reply to  moczul

HI moczul,

Those articles will be soon….

vickysadhu
vickysadhu
9 years ago

can work on android 1.5 version?

Ravi Tamada
9 years ago
Reply to  vickysadhu

I haven’t tried … but it should work.

Chichi369
Chichi369
8 years ago
Reply to  Ravi Tamada

Hi Ravi, can u tell me what kind of android build target for all your tutorial, thanks for reply

Ravi Tamada
8 years ago
Reply to  Chichi369

I used Android 2.2 target for all my tutorials.

Chichi369
Chichi369
8 years ago
Reply to  Ravi Tamada

Sorry, i have another questions, i start to develop a audience response system for my website and android mobile device, the website should let presenter create some questions such as MC, LQ, open end question, checkbox question,etc in a session (polling) and users can join that session to vote their choices,

and for android mobile users, they can join that session to vote questions. for my questions are.. should i use JSON or XML to store questions list in my website in MYSQL database and what technology must implement to let mobile user to join session and during the session user can vote their choices based on current questions, sorry for my stupid question, but i have no ideas about android technology

Chichi369
Chichi369
8 years ago
Reply to  Ravi Tamada

Hi Ravi, also i wanna know the difference between the value of fill_parent and match_parent, i confuse this two

Ravi Tamada
8 years ago
Reply to  Chichi369

both do same job, but from API Level +8 fill_parent is deprecated. You have to use match_parent only.

Chichi369
Chichi369
8 years ago
Reply to  Ravi Tamada

Hi Ravi, can u give me some ideas for my below questions, thanks

Chichi369
Chichi369
8 years ago
Reply to  Ravi Tamada

Ravi, please give me a direction of this situation, just should i use JSON or XML to store questions list in my website in MYSQL database and what technology must implement to let mobile user to join session and during the session user can vote their choices based on current questions, sorry for my stupid question, but i have no ideas about android technology~thanks

Ravi Tamada
8 years ago
Reply to  Chichi369

Use JSON for your application as it is more flexible than XML. Just send a request from mobile to get all questions. From mobile if user votes a question just send question id along with user id to your api. There change in your database of the question (vote up / down question by user id)

Jimmy
Jimmy
8 years ago
Reply to  Ravi Tamada

but, should i store JSON file in database coloum (store the path of file) or is there else other alternative to store questions list file? thanks for reply

Ravi Tamada
8 years ago
Reply to  Jimmy

We should not store JSON in database. Store only questions in database. When required get the questions from database and generate the json on the fly and echo.

If you are using PHP get the data from database. Store them in Array in convert array into json using json_encode($your_array) function. Google about converting array to json in php.

Jimmy
Jimmy
8 years ago
Reply to  Ravi Tamada

but, u said that i cant store JSON in database, Store only questions in database that mean pain text file’s path on the server??

Ravi Tamada
8 years ago
Reply to  Jimmy

I mean question in database table like

table structure
——————-
qid | question | created_at
1. | Your question | 12:30 PM 12-12-2011

Jimmy
Jimmy
8 years ago
Reply to  Ravi Tamada

but if there are many questions in a session, that mean i should store every question record in question table and then use get all questions about that session and convert TO JSON, then , form mobile just make request and parse JSON ?

HRJ
HRJ
9 years ago

Coincidentally, I am implementing a project to simplify the HTTP request model for Android. It’s an open source project that you can find here:
https://github.com/hrj/SafeNet

Balwazar
Balwazar
9 years ago

Hi,

I was trying to implement similar code to log in https page and display response content in webView but it seems to fail? have you any idea why?

Idle Brain
Idle Brain
9 years ago

StrictMode is enabled by default in Android 3.0 and above. Hence, this code might not work. You have to do this in a separate Thread or even better an AsyncTask.

Ravi Tamada
9 years ago
Reply to  Idle Brain

Thanks for the information.

Jignesh
Jignesh
9 years ago

i had a doubt about making http requests to gmail…
my app stores the login details of gmail account.
wat i wanna do is whn user clicks on the login , it must automatically login into gmail & show his inbox in the browser.

m really new to android…please help

Ravi Tamada
9 years ago
Reply to  Jignesh

You need to implement OAuth to connect to gmail:
http://googlecode.blogspot.in/2010/03/oauth-access-to-imapsmtp-in-gmail.html

Saša Karanović
9 years ago

I was getting errors from debugger until I added

in my AndroidManifest.xml.

Keshav
Keshav
9 years ago

dear ravi this is only post the data right how can i give read the data in smae file. like sucess message.

Ravi Tamada
9 years ago
Reply to  Keshav

I didn’t get you clearly. Could you explain me better ?

Keshav Php
Keshav Php
9 years ago
Reply to  Ravi Tamada

dear ravi i am able to post the data but when i given the success message it’s not display like

Cooltey
9 years ago
Reply to  Keshav Php

I think that your question could be solved by the following code.

InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
String html = str.toString();

Idris Tarwala
Idris Tarwala
9 years ago

hi Ravi i tried ur code but it doesnt work and keeps giving an error, i also added a uses-permission for the internet , but it still gives me an error , kindly suggest a solution

Ravi Tamada
9 years ago
Reply to  Idris Tarwala

Make sure that you added permission outside tag not inside. If you did correctly please check for your error log cat report.

Idris Tarwala
Idris Tarwala
9 years ago
Reply to  Ravi Tamada

hi this is how my manifest loks like…kindly suggest wat is wrong

Ravi Tamada
9 years ago
Reply to  Idris Tarwala

It seems to be correct. Check your error log report.
Windows -> Show View -> Other -> Android -> Log Cat

Idris Tarwala
Idris Tarwala
9 years ago
Reply to  Ravi Tamada

the application crashes…is tht suppose to happen ??

Idris Tarwala
Idris Tarwala
9 years ago
Reply to  Idris Tarwala

this is the logcat i get

02-15 07:27:15.627: E/AndroidRuntime(1397): Uncaught handler: thread main exiting due to uncaught exception
02-15 07:27:15.746: E/AndroidRuntime(1397): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aiindia.prometheus/com.aiindia.prometheus.AndroidHTTPRequestsActivity}: java.lang.ClassNotFoundException: com.aiindia.prometheus.AndroidHTTPRequestsActivity in loader dalvik.system.PathClassLoader@44c07938
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.os.Handler.dispatchMessage(Handler.java:99)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.os.Looper.loop(Looper.java:123)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread.main(ActivityThread.java:4363)
02-15 07:27:15.746: E/AndroidRuntime(1397): at java.lang.reflect.Method.invokeNative(Native Method)
02-15 07:27:15.746: E/AndroidRuntime(1397): at java.lang.reflect.Method.invoke(Method.java:521)
02-15 07:27:15.746: E/AndroidRuntime(1397): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
02-15 07:27:15.746: E/AndroidRuntime(1397): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
02-15 07:27:15.746: E/AndroidRuntime(1397): at dalvik.system.NativeStart.main(Native Method)
02-15 07:27:15.746: E/AndroidRuntime(1397): Caused by: java.lang.ClassNotFoundException: com.aiindia.prometheus.AndroidHTTPRequestsActivity in loader dalvik.system.PathClassLoader@44c07938
02-15 07:27:15.746: E/AndroidRuntime(1397): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
02-15 07:27:15.746: E/AndroidRuntime(1397): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
02-15 07:27:15.746: E/AndroidRuntime(1397): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
02-15 07:27:15.746: E/AndroidRuntime(1397): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
02-15 07:27:15.746: E/AndroidRuntime(1397): … 11 more
02-15 07:27:15.815: E/dalvikvm(1397): Unable to open stack trace file ‘/data/anr/traces.txt’: Permission denied

Ravi Tamada
9 years ago
Reply to  Idris Tarwala

It is problem with your AndoridManifest.xml file. Something goes wrong. Please download my files compare them correctly.

Amit Tiwari
Amit Tiwari
8 years ago
Reply to  Idris Tarwala

you have to add this permission also to you manifast

Tagoeronald
Tagoeronald
9 years ago

hello Ravi i downloaded the source code and it did not work
the app suddenly crashes when i ht the register or login button

fedooooo
fedooooo
8 years ago

hi ravi thx for this Example, i downloaded the source code and it did not work it crash i just want to know do i have to change this element with my real @email and password so the exampel will work ?
i didn t get how what i have to expect like a response for this application §??
this is what i understand : the application wil send an email to my email box ? right !!! pls & thx
SORRY I KNOW I HAVE MANY qst but i m new with android

Ravi Tamada
8 years ago
Reply to  fedooooo

Hi fedo,

I gave an example of email and password field. You can send whatever data you want, that depends on your app requirement. Please check for Permissions in you AndroidManifest.xml file.

the application wil send an email to my email box ? – It won’t send email to your email box. It is an example of when user log into their application i am sending their email and password to a online server. There you need to check email and password are in database. if yes send success response to client mobile or send fail response.

I think i missed one point in this tutorial. Add internet permission in your androidmanifest.xml file after tag

Then also if it don’t work give me your error log cat.

peter cuteberg
peter cuteberg
8 years ago

Hi ravi
i tried to adapt this code to my applicating, for example, instead of sending the paametre email with its value i send with the Http request the city parametre with the name of the city that i want to show its data as a value, but i always get the data of the default city which is casablanca and not the data of the targeted city

can you help me please abd thanks

Ravi Tamada
8 years ago
Reply to  peter cuteberg

can u give some code of your’s

Amey Joshi
8 years ago

Hi Ravi,
I want source code for calculating total price for all shopping items and to display them in a separate list,will you please help me,since i’m a beginner

138
0
Would love your thoughts, please comment.x
()
x