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);
}
Related
This is my code for Android:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Submit Successfully";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
This is the error:
07-21 12:55:35.297 24973-24973/com.futegolo.igomessenger W/System.err:
org.json.JSONException: Value Data of type java.lang.String cannot be
converted to JSONObject
This is my json response
{"status":0}
This is because you are not returning the actual response from service in doInBackground() method. You are returning as
return "Data Submit Successfully"
And when you convert that string in onPostExecute() method obviously that is not valid JsonObject
Replace your code after this "HttpEntity entity = response.getEntity();"
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
And rather returning your hard coded string return result. Hope that helps.
for further reference you can follow below links
https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
Use the code as following:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringBuffer result= new StringBuffer();
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
Appache has already provided a Util class for that called EntityUtils.
Replace return "Data Submit Successfully" with this code
String responseText = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
return responseText;
NODE.js : (zip the file)
app.post('/api/db', function(req, res){
if(req.body.type == 'Control'){
var zip = new AdmZip();
console.log(req.body.type);
zip.addLocalFolder(__dirname +'/XXX/Temp/1');
var willSendthis = zip.toBuffer();
zip.writeZip(__dirname +'/files.zip');
res.sendFile(zip);
}
});
JAVA : (send a request to want to zip file)
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
public ArrayList<String> aList= new ArrayList<String>();
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "Control"));
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String result) {
}
}
JSON PARSER:
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));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "PUT"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
url = url.trim();
Log.d("url = ", URLEncoder.encode(url, "UTF-8"));
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
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-9"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
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;
}
}
I sent .zip file from server to android devices. I want to save into the android devices memory.
How can i save .zip file which is sended by node.js server?
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();
I'm want to make User register system.. I'm using Facebook SDK and I can send user information my Database from comes to Facebook and successfully registered. But I want to show different fragment activity after this.
If user access my application on Facebook, I'm sending users data Async Class (different class not inner class)
In the summary when my server return the Json data I want to close MainFragmentActivity class and open StartFragmentActivity
I couldn't do it in onPostExecute function with Intent. How can I do it ?
Thanks for help and I'm sorry my poor English
private void makeRequest(final Session session){
Log.d("deneme","makeRequest ÇALIŞIYOR");
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if(session == Session.getActiveSession()){
if(user != null){
new MyAsyncTask(getActivity(), "ssoLR", user.getName(),
user.getId(), user.getProperty("email")
.toString());
}
}
}
});
request.executeAsync();
}
My AsyncTask Class like this,
public class MyAsyncTask extends AsyncTask<String, Integer, Double> {
public MyAsyncTask(FragmentActivity a, String tag, String username, String password, String email){
this.mMain = a;
this.tag = tag;
this.username = username;
this.password = password;
this.email = email;
execute(tag, username, password, email);
}
#Override
protected Double doInBackground(String... params) {
if(tag.equals("ssoLR")){
postData(params[0], params[1], params[2], params[3]);
}
return null;
}
public void postData(String tag, String username, String password, String email) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<my website");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", tag));
nameValuePairs.add(new BasicNameValuePair("name", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
protected void onPostExecute(Double result){
try {
InputStream inputStream = response.getEntity().getContent();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
stringbuilder = new StringBuilder();
String buffer = null;
while((buffer = bufferedreader.readLine()) != null){
stringbuilder.append(buffer);
}
} catch (IllegalStateException e) {
} catch (IOException e) {
}
}
protected void onProgressUpdate(Integer... progress){
}
HttpResponse response;
StringBuilder stringbuilder;
private String tag, username, password, email;
}
Here's my java code:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
postParameters.add(new BasicNameValuePair("username", txtUsername.getText().toString()));
postParameters.add(new BasicNameValuePair("password", txtPassword.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://www.sampleweb.com/imba.php", postParameters);
String res = response.toString();
// res = res.trim();
res = res.replaceAll("\\s+", "");
//error.setText(res);
if (res.equals("1")) {
txtError.setText("Correct Username or Password");
//Intent i = new Intent(CDroidMonitoringActivity.this, MenuClass.class);
//startActivity(i);
} else {
txtError.setText("Sorry!! Incorrect Username or Password");
}
} catch (Exception e) {
txtUsername.setText(e.toString());
}
}
});
I thinks there's an error in my res.equals because it keeps saying "Invalid Username or password" even though I've entered the correct username or password. But when I change the res.equals to res.contains it keeps saying "correct username or password" even though i've entered the correct username and password. I really need your help. to all mastered in android development. Hope you could help me on this. And also, when i change the txtError.setText(res) just to check if it returns 1 and 0 it does not.
This needs to be done in the php file not in the Android code:
<?php
define('DB_USER', "root"); //username used to connect to the database.
define('DB_PASSWORD', ""); //password used to connect to the database.
define('DB_DATABASE', "dbname"); //database name
define('DB_SERVER', "127.0.0.1"); //database server address
?>
Using a JSON parser, you would then need to parse the data on the server. You need to use something similar to the following:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//Method to connect to the database
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//The following works just as in normal GET and POST methods
try {
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) {
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;
}
}
In a second class, you would then need to define the connection parameters as follows:
public class UserFunctions {
private JSONParser jsonParser;
private static String loginURL = "http://www.sampleweb.com/login.php";
private static String registerURL = "http://www.sampleweb.com/register.php";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
In addition to this, you would finally need to use your application classes to parse data and show it to the users. There are several online tutorials on how this can be done.
Hope this helps :)
It is really difficult to figure out what is going on with out the response from server. To debug the issue, for both valid and invalid user name/password combinations check the response of http://www.sampleweb.com/imba.php using a POST library like curl or Postman