i have wrote a method to send some data to server and receive a integer value :
private void sendOrder(Order order,String cid) {
InputStream inputStream = null;
String result = "";
int statusCode = 0;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(send_url);
JSONArray jsonArray = new JSONArray();
for (OrderDetails detail : order.getOrders()) {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("c_id", cid);
jsonObject.accumulate("r_id", String.valueOf(detail.getR_id()));
jsonObject.accumulate("f_id", String.valueOf(detail.getF_id()));
jsonObject.accumulate("count",
String.valueOf(detail.getCount()));
jsonArray.put(jsonObject);
}
String json = jsonArray.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = Util.convertInputStreamToString(inputStream);
else
result = "0";
} catch (Exception e) {
Log.d("send order", e.toString());
}
Log.d("order result", result);
return Integer.parseInt(result);
}
the cid is numbers stored in a string like : "30111"
but in the server there is a problem in receiving c_id. its's value in server is like :"c_id":"\"30111\""
i want to c_id to be in the server as same as it is in the client.
how can i fix that ? UPDATE this is my json string in android log :
[{"count":"1","r_id":"8","f_id":"10033","c_id":"\"30111\""},{"count":"2","r_id":"8","f_id":"10034","c_id":"\"30111\""}]
This is my code, working really fine
Make a class -
public class AddQuery extends AsyncTask<Void, Void, Void> {
private Context context;
private ProgressDialog pd;
private String url;
private String jsonResult;
private String qrs;
private String cId;
public AddQuery(Context context, String qrs, String cid) {
// TODO Auto-generated constructor stub
this.context = context;
this.qrs = qrs;
this.cId = cid;
url = "http://" + context.getResources().getString(R.string.url)
+ "/ques.php";
pd = new ProgressDialog(context);
pd.setIndeterminate(true);
pd.setMessage("Retrieving Data..");
pd.setCancelable(false);
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = context.getSharedPreferences("com.multisoft",
Context.MODE_PRIVATE);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("go", "add"));
params.add(new BasicNameValuePair("qrs", qrs));
params.add(new BasicNameValuePair("cid", cId));
params.add(new BasicNameValuePair("uid", prefs.getString("userID", "0")));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
JSONObject jsonResponse;
jsonResponse = new JSONObject(jsonResult);
//do what you want to do here from text apeared from your php and stored in jsonResult
String c_id = jsonResponse.optString("c_id");
}
execute the above class in your main activity like this-
new AddQuery(MyActivity.this, "4","23").execute();
Related
I need to send a string obtained from EditText in android to the PHP to be used as an id to query the database. So, I got the string from EditText as follows:
childIDVal = childID.getText().toString();
Toast.makeText(getApplicationContext(),childIDVal,Toast.LENGTH_LONG).show();
// To do : transfer data to PHP
transferToPhp(childIDVal);
So, what should my transferToPhp() contain? And also the php code is:
<?php
if( isset($_POST["ChildID"]) ) {
$data = json_decode($_POST["ChildID"]);
$data->msg = strrev($data->msg);
echo json_encode($data);
}
Is it okay? I am a newbie to both android and Php, so i need some help right now. Thanks!
I' m offering you to use AsyncTask which reaches PHP file existing in your server using HttpClient:
/*Sending data to PHP and receives success result*/
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResults = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// SENDING PARAMETERS WITH GIVEN NAMES
nameValuePairs.add(new BasicNameValuePair("paramName_1", params[1]));
nameValuePairs.add(new BasicNameValuePair("paramName_2", params[2]));
// ...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResults = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResults;
}
// DO SOMETHING BEFORE PHP RESPONSE
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// DO SOMETHING AFTER PHP RESPONSE
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("") || result.equals(null)){
return;
}
// Json response from PHP
String jsonResult = returnParsedJsonObject(result);
// i.e.
if (jsonResult.equals("some_response") {
// do something
}
}
// READING ANSWER FROM PHP
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
// GET ALL RETURNED VALUES FROM PHP
private String returnParsedJsonObject(String result){
JSONObject resultObject;
String returnedResult = "0";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("response");
String value1 = resultObject.getString("value1");
String value2 = resultObject.getString("value2");
//...
// do something with retrieved values
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
To send some parameters use:
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute("server_url", param1, param2,...);
Hope it helps you.
I am trying to send request to the server and getting a redirect URL as a response {"redirect url":"http://192.168.1.95"} from the server and again I want to send a request to the redirect URL.
I am getting Error:the Connection to http://192.168.1.95 refusedin android.In iOS it works fine.
Please help me to solve this problem.
private void Signup(final String firstname,final String lastname,String email, String password,String action,String path) {
class SignupAsync extends AsyncTask<String, Void, String>{
// private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
#Override
protected String doInBackground(String... params) {
String fname = params[0];
String lname = params[1];
String email = params[2];
String password = params[3];
String action = params[4];
String finalpath1=params[5];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", email));
nameValuePairs.add(new BasicNameValuePair("firstname", fname));
nameValuePairs.add(new BasicNameValuePair("lastname", lname));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("_action", action));
String result = null;
String finalpath;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost=null;
if (finalpath1 != null){
httpPost = new HttpPost(finalpath1);
}
else{
httpPost = new HttpPost("http://192.168.1.122");
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=null;
response = httpClient.execute(httpPost);
HttpEntity entity = null;
entity= response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String finalpath = result;
if(finalpath != null)
{
SignupAsync la1 = new SignupAsync();
la1.execute("firstname","lastname","em#h.n","kkkjpass","REGISTERUSER",finalpath); }
}
}
SignupAsync la = new SignupAsync();
la.execute(firstname,lastname,email,password,action,path);
}
I want to carry out the following php query on my remote database
$result = mysqli_query($con->myconn, "SELECT id, stake, user, returns, teams, status FROM `bet` WHERE user = $user") or die(mysql_error());
My only problem is I'm not sure how to modify my JSONParser class so that I can simultaneously pass the user parameter to the database and receive the results. It currently looks like this and allows me only to either retrieve values or send values.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CODE :
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "***";
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
JSONArray allgames = null;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
// Hashmap for ListView
ArrayList<HashMap<String, String>> gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
*/
/**
* Before starting background thread Show Progress Dialog
*//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Bets. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
*/
/**
* getting All products from url
*//*
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
stake = c.getString(TAG_STAKE);
returns = c.getString(TAG_RETURNS);
status = c.getString(TAG_STATUS);
teams = c.getString(TAG_TEAMS);;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, teams);
map.put(TAG_STAKE, stake);
map.put(TAG_RETURNS, returns);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
gamesList.add(map);
}
// } else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}
In order to avoid executing the http relating things in the UI thread, i migrated my code inside asynctask, before that, it was working fine on versions before 3.0 -- however, after literally copy pasting the code inside asynctask, it started to giving the invalid index, size is 0 exception. Whenever I need to use the method I am applying the call --
new dataRetrievalViaAsyncTask().execute(url, null, null); --
Whats wrong down there ?
class dataRetrievalViaAsyncTask extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
// convert response to string
return null;
}
protected void onPostExecute()
{
try
{
Log.i("tag","before : BufferedReader reader = new BufferedReader(new Inp");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
try
{
Log.i("tag", "before : jsons ");
jArray = new JSONArray(result);
JSONObject json_data = null;
Log.i("tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
uid = json_data.getInt("uid");
item1= json_data.getString("item1");
item2 = json_data.getString("item2");
item3 = json_data.getString("item3");
item4 = json_data.getString("item4");
item5 = json_data.getString("item5");
item6 = json_data.getString("item6");
favorited = json_data.getString("favorited");
currentList.add(new itemClass(uid, item1 item2)); //there is a constructor for this in the itemClass
itemClass toSendToOffline = new itemsClass(uid, item1, item2, item3, item4, item5, item6, favorited);
myDBHelper.insertFromOnlineToDBtoSendToOffline();
}
} catch (JSONException e1)
{
Toast.makeText(getBaseContext(), "Not Found", Toast.LENGTH_LONG).show();
} catch (ParseException e1)
{
e1.printStackTrace();
}
super.onPostExecute(null);
}
}
(mainly the code is stopping at --
HttpResponse response = httpclient.execute(httppost);
I can not see nameValuePairs variable initialized anywhere, which is actually causing problem.
class dataRetrievalViaAsyncTask extends AsyncTask<Void, Void, String>
{
String URL = "";
public dataRetrievalViaAsyncTask( String url )
{
URL = url;
}
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... f_url)
{
String result="";
try
{
result=fetchdataFromServer(URL);
}
catch (JSONException e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
// See your results as string //result
}
public JSONObject getJsonObjectToRequestToServer(String plid) throws JSONException
{
JSONObject parms = new JSONObject();
parms.put("user_id", "");
parms.put("app_key", "xyz");
parms.put("secret", "abc");
parms.put("token", "");
parms.put("playurl", "1");
parms.put("mode", "playlistdetail");
parms.put("playlist_id", plid);
return parms;
}
public String fetchdataFromServer(String url) throws JSONException
{
String stringresponce = null;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject parms = getJsonObjectToRequestToServer("1");
StringEntity se;
se = new StringEntity(parms.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
#SuppressWarnings("rawtypes")
ResponseHandler responseHandler = new BasicResponseHandler();
stringresponce = httpClient.execute(httpPost, responseHandler);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return stringresponce;
}
}
put this code in your code and pass arguments ass you need this is the way how i request to server and get json response as string from result variable pass arguments to your url as i passed by making json object then convert them to string
then execute like this............
dataRetrievalViaAsyncTask asyncTask=new dataRetrievalViaAsyncTask(Yoururl);
asyncTask.execute();
hope this will help if you have some issues please post here thanks......
I want to call a rest webservice with POST method.Below is the service url and its parameters which I need to pass
Rest Service: https://url/SSOServer/SSO.svc/RestService/Login
Json Object {"ProductCode":"AB","DeviceType":"android Simulator","UserName":"","ModuleCode":"AB_MOBILE","DeviceId":"device-id","Version":"1.0.0.19","CustomerCode":"w","Password":""}
Here is my post request code:
public void sendHttpPost() throws ClientProtocolException, IOException{
HttpPost httpPostRequest = new HttpPost(url + buildParams());
// add headers
Iterator it = headers.entrySet().iterator();
Iterator itP = params.entrySet().iterator();
while (it.hasNext()) {
Entry header = (Entry) it.next();
httpPostRequest.addHeader((String)header.getKey(), (String)header.getValue());
}
HttpClient client = new DefaultHttpClient();
HttpResponse resp;
resp = client.execute(httpPostRequest);
this.respCode = resp.getStatusLine().getStatusCode();
Log.i(TAG, "response code: " + getResponseCode());
this.responsePhrase = resp.getStatusLine().getReasonPhrase();
Log.i(TAG, "error msg: " + getErrorMsg());
HttpEntity entity = resp.getEntity();
if (entity != null){
InputStream is = entity.getContent();
//Header contentEncoding = resp.getFirstHeader("Content-encoding");
//Log.i(TAG, "endoding" + contentEncoding.getValue());
response = convertStreamToString(is);
//response = response.substring(1,response.length()-1);
//response = "{" + response + "}";
Log.i(TAG, "response: " + response);
is.close();
}
}
My question is how to add json data to this request??
Use below class
public class RestClient
{
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse()
{
return response;
}
public String getErrorMessage()
{
return message;
}
public int getResponseCode()
{
return responseCode;
}
public RestClient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch (method)
{
case GET:
{
// add parameters
String combinedParams = "";
if (!params.isEmpty())
{
combinedParams += "";
for (NameValuePair p : params)
{
String paramString = p.getName() + "" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty())
{
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url) throws Exception
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
private static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
public InputStream getInputStream(){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try
{
HttpPost request = new HttpPost(url);
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
return instream;
/* response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();*/
}
}
catch (ClientProtocolException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return null;
}
public enum RequestMethod
{
GET,
POST
}
}
Here is the code how to use above class
RestClient client=new RestClient(Webservices.student_details);
JSONObject obj=new JSONObject();
obj.put("StudentId",preferences.getStudentId());
client.AddParam("",obj.toString());
client.Execute(RequestMethod.GET);
String response=client.getResponse();
Hope this will help you
Q: how to add json data to this request?
A: Set your content type, length and write the payload.
Here's an example:
http://localtone.blogspot.com/2009/07/post-json-using-android-and-httpclient.html
JSONObject holder = new JSONObject();
...
JSONObject data = new JSONObject();
...
// Some example name=value pairs
while(iter.hasNext()) {
Map.Entry pairs = (Map.Entry)iter.next();
String key = (String)pairs.getKey();
Map m = (Map)pairs.getValue();
JSONObject data = new JSONObject();
Iterator iter2 = m.entrySet().iterator();
while(iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
holder.put(key, data);
}
...
StringEntity se = new StringEntity(holder.toString());
...
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
...