I am working on a small test app that communicates with my website. It makes an HttpPost with credentials in order to see if the user is registered.
However, for some reason the post is made instantaniously even though it's supposed to take a second and it's always empty. It's a class I used about a year ago, was working back then.
private class LoginTask extends AsyncTask<String, Integer, String> {
private HashMap<String, String> mData = null;// post data
public String serverResult = "";
/**
* constructor
*/
public LoginTask(HashMap<String, String> data) {
mData = data;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
serverResult = str;
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
serverResult = result;
pb.setVisibility(View.GONE);
if(serverResult == "no")
{
Toast t = Toast.makeText(MainActivity.this, "Login failed. Correct username or password", Toast.LENGTH_LONG);
t.show();
}
else if (serverResult.contains("email"))
{
Toast t = Toast.makeText(MainActivity.this, "HELLOOOOO", Toast.LENGTH_LONG);
t.show();
}
else
{
Toast t = Toast.makeText(MainActivity.this, "Server error: " + serverResult, Toast.LENGTH_LONG);
t.show();
}
}
protected void onProgressUpdate(Integer... progress) {
pb.setProgress(progress[0]);
}
}
The information sent to the server is definitely correct and should retrieve SOME message back, but here it's always empty. Maybe something in the background process is wrong.
What's going on in the logcat ? Do you have any exception there ?
And did you add the internet permission into your manifest ?
<uses-permission android:name="android.permission.INTERNET" />
Related
Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public 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("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 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 = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
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;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.
My client type is android and the language is Java.
This class connects to the server and gets the output stream to the connected server.
class ConnectToServer extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params)
{
try {
socket = new Socket(ip,port);
output = new DataOutputStream(socket.getOutputStream());
Log.d(TAG, "Connected To Server!");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
class SendToServer extends AsyncTask<Void, Void, Void>
{
//Our Json object
JSONObject obj;// = new JSONObject();
//this class is called when the login button is pressed, it sends the username and password as arguments
public SendToServer(String username, String password)
{
//instantiate the new object
obj = new JSONObject();
try {
//create the first field Type
obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request
obj.put("username", username); //our server will get username
obj.put("password",password); //our server will get password
} catch (JSONException e) {
e.printStackTrace(); //if we get problems let the developer know
}
}
#Override
protected Void doInBackground(Void... params)
{
String jsonText = obj.toString(); //convert our json object into a string
byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array
try {
output.writeInt(b.length); // write length of the message
output.write(b); // write the message
output.flush(); //flush - empties the pipe
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
The purpose of this code is to send the server the users credentials.
In this C# Server
private void serverClient()
{
while(true)
{
int len = ns.ReadByte(); //read how much data
if (len == 0) //if this == 0 this means client has quit the program
break; //break out of loop and remove client from array list
if (len > 0) //we have a message
{
//read mess
byte[] message = new byte[len]; //create byte array
ns.Read(message, 0, message.Length); //read into the message byte array
string text = Encoding.ASCII.GetString(message, 0, len);
string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got.
Console.WriteLine(text1);
}
}
removeClients();
}
So the Android client will send the credentials, but when the SendToServer class is called, the client disconnects from the server.
How can I send a Json string to my C# server so it can then read the string and serialize it into an object, depending on the fields.
private void updateDataToServer() {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_update);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1) {
/*
* Toast.makeText(getBaseContext(), "Update Successfully",
* Toast.LENGTH_SHORT).show();
*/
} else {
Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
}
class PostDataToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
* pDialog = new ProgressDialog(MainActivity.this);
* pDialog.setMessage("Please wait..."); pDialog.show();
*/
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_create_product);
try {
name = edt_name.getText().toString();
score = edt_score.getText().toString();
quocgia = edt_quocgia.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("score", score));
nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
#Override
protected void onPostExecute(String s) {
/*
* if (pDialog.isShowing()) { pDialog.dismiss();
* Toast.makeText(getApplication(), "Complete",
* Toast.LENGTH_LONG).show(); }
*/
}
}
Hope it helps you
You're reading lines but you aren't writing lines. Add a line terminator to the message being sent, or use println() instead of write().
Need to println HttpResponse response if the conexion is fail
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
#Override
protected String doInBackground(String... params) {
return GET();
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Iniciando sesión...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
}
public String GET() {
String url = "http://"+ippref+":8080/Activo/webresources/activo.entities.coreusuario/usuarios/" + usuario_ws + "/" +contrasenia_ws+ "";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
response.getStatusLine().getStatusCode();
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
Need printl the statuscode
Check for return status. If its value is not 200 then its a failure and toast it.
if(response.getStatusLine().getStatusCode()!=200){
Toast.makeText(getApplicationContext(),
"Request failure!",
Toast.LENGTH_LONG).show();
}
Use this :
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode(),
Toast.LENGTH_LONG).show();
import android.widget.Toast
And you can change time of toast by changing Toast.LENGTH_LONG
Of course if you want to only show toast when http response is bad,then add the logic for checking the error cases and make toast there.
Hope this helps. :)
when I sent post login data use login button like this :
loginbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String user = email.getText().toString().trim();
final String pwd = password.getText().toString().trim();
if (email.getText().toString().equals("")) {
Utils.toast(context, "Username empty...");
} else if (password.getText().toString().equals("")) {
Utils.toast(context, "Password empty...");
} else if (!isValidEmail(user)) {
email.setError("Invalid Email");
} else if (user.length() < 2) {
Utils.toast(context, "Username to short...");
} else if (pwd.length() < 2) {
Utils.toast(context, "Password to short...");
} else if (!isValidPassword(pwd)) {
password.setError("Invalid Password");
} else {
progress.setVisibility(View.VISIBLE);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(user, pwd);
}
}
});
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "UserLoginTask";
#Override
protected String doInBackground(String... params) {
String user = params[0];
String pwd = params[1];
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("email", user ));
postParameters.add(new BasicNameValuePair("password", pwd ));
String responseString = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.219:90/auth/login");
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(response.getEntity());
Utils.log("daftar isi: " + responseAsText);
JSONObject loginjson = new JSONObject(responseAsText);
Utils.log("json object: " + loginjson);
String roleString = loginjson.getString("role");
Utils.log("role: " + roleString);
if(roleString.equals("member")){
Intent intent = new Intent(context, home.class);
startActivity(intent);
}else if(roleString.equals("studio")){
Intent intent = new Intent(context, VendorDashboard.class);
startActivity(intent);
}
}
catch (Exception e)
{
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
#Override
protected void onPostExecute(String message) {
//process message
}
}
actually it will get feedback JSON response like this :
{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNCIsImlzcyI6Imh0dHA6XC9cLzE5Mi4xNjguMC4yMTk6OTBcL2F1dGhcL2xvZ2luIiwiaWF0IjoiMTQ0NTI0NzIyMSIsImV4cCI6IjE0NDY0NTY4MjEiLCJuYmYiOiIxNDQ1MjQ3MjIxIiwianRpIjoiNTY4MDEyZDUwNTg1NDFjM2UzNGVjMGViYzMzZDkzMGQifQ.zw5c5kLIlvPYIMhEzEnF_fCOu77XTq2prcDtSHJY7bk","role":"studio"}
How to get role (JSON response feedback) so I can use if and else if statement after execute HTTP Post Request (after Utils.toast(context, responseAsText);)?
Update after I used asynctask, it did not produce error onclick.
Update it is done. Thanks mr.shreyash.
Question closed.
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(“http://www.example.com/example/fileUpload.php”);//example site
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
/**
* Method to show alert dialog
* */
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
PHP CODE FOR SERVER fileUpload.php
<?php
// Path to move uploaded files
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
// reading other post parameters
$email = isset($_POST['email']) ? $_POST['email'] : '';
$website = isset($_POST['website']) ? $_POST['website'] : '';
$response['file_name'] = basename($_FILES['image']['name']);
$response['email'] = $email;
$response['website'] = $website;
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
$response['error'] = true;
$response['message'] = 'Could not move the file!';
}
// File successfully uploaded
$response['message'] = 'File uploaded successfully!';
$response['error'] = false;
$response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
$response['error'] = true;
$response['message'] = $e->getMessage();
}
} else {
// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}
// Echo final json response to client
echo json_encode($response);
?>
Above code response to client below error:
httpResponse is not responding. Exception come as org.apache.http.NoHttpResponseException: The target server failed to respond.
HttpResponse response = httpclient.execute(httppost);
Please try this code:
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}