I have a problem with my code that works very well for me, but when I intercept with a proxy it sends me a double request. I would like to solve that error and only send it once. I was checking the web and I found a similar question but I am new to this language and I don't know how to implement it.
Android Volley double post when have slow request
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.pwd);
final Button loginButton = findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String URL = "https://www.myurl.com/login.php";
String username = usernameEditText.getText().toString();
String pwd = passwordEditText.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject r = new JSONObject(response);
String status = r.getString("msg");
if (status.equals("OK")) {
Intent secretIntent = new Intent().setClass(LoginActivity.this, MenuActivity.class);
startActivity(secretIntent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("pwd", pwd);
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
hello I could find the answer, it was actually very simple just add a line to the code
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
here my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.pwd);
final Button loginButton = findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String URL = "https://www.myurl.com/login.php";
String username = usernameEditText.getText().toString();
String pwd = passwordEditText.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject r = new JSONObject(response);
String status = r.getString("msg");
if (status.equals("OK")) {
Intent secretIntent = new Intent().setClass(LoginActivity.this, MenuActivity.class);
startActivity(secretIntent);
finish();
} else {
Toast.makeText(LoginActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("pwd", pwd);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
});
}
Related
when i click login button, that alert will show up, i use com.android.volley:volley:1.1.1
and for api, i use restframework from python
this is my mainactivity.java code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
username = etUsername.getText().toString();
password = etPassword.getText().toString();
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
String urlLogin = "http://10.0.3.2/api/accounts";
StringRequest stringRequest = new StringRequest(Request.Method.POST, urlLogin, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try {
JSONObject jsonObject = new JSONObject(response);
boolean validasiLogin = jsonObject.getBoolean("success");
Toast.makeText(MainActivity.this, validasiLogin+"", Toast.LENGTH_SHORT).show();
if (validasiLogin) {
String jsonUsername = jsonObject.getString("username");
Toast.makeText(MainActivity.this, "Username : "+jsonUsername, Toast.LENGTH_LONG).show();
Intent bukaIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(bukaIntent);
}else {
Toast.makeText(MainActivity.this, "Username / Password Salah", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0){
Toast.makeText(MainActivity.this, arg0+"", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
}
how to fix it? can u show what wrong with my code pliss?
Try to debug and see if arg0 in public void onErrorResponse(VolleyError arg0) contains any useful information. Or you can try to log error response body like here: https://stackoverflow.com/a/30722575/5148282
maybe it will help you
fun onErrorResponse(error: VolleyError?) {
if (error == null || error.networkResponse == null) {
return
}
val body: String
//get status code here
val statusCode: String = java.lang.String.valueOf(error.networkResponse.statusCode)
//get response body and parse with appropriate encoding
try {
val UTF_8: Charset = Charset.forName("UTF-8")
body = String(error.networkResponse.data, UTF_8)
} catch (e: UnsupportedEncodingException) {
// exception
}
//do stuff with the body
}
i have a server side api method which accept Model class as a parameter
which does work fine i have checked it but from android i am confused how to send a Model class as a parameter?
public class Login extends AppCompatActivity {
EditText email, password;
String Email, Pass;
Button loginbtn;
String URL = "https://192.168.0.102/api/campaign/Logins";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
handleSSLHandshake();
email = findViewById(R.id.input_email);
password = findViewById(R.id.password);
loginbtn = findViewById(R.id.login_button);
final RequestQueue queue = Volley.newRequestQueue(this);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Email = email.getText().toString();
Pass = password.getText().toString();
StringRequest postRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
params.put("email", Email);
params.put("password", Pass);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
queue.add(postRequest);
}
});
This is what i have tried i know the problem is from the server side can anyone help me what i am thinking is the problem or is there anything else ?
You just need to add a JSONObject with the post parameters as key-value pairs in the JSON Object. Here is the example for you:
JSONObject postparams = new JSONObject();
postparams.put("keyX", "valueX")
postparams.put("KEY", "Value")
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
i am trying to post data on server using volley but it just give me Volley.ServerError when i click on submit button.But also When i debug my app then all parameters get value but instead of that their is error.
public class ConnectWithSpeaker extends AppCompatActivity implements
View.OnClickListener {
LinearLayout linear_layoutcontainer;
Toolbar toolbar;
String url = Constants.SUBMIT_API;
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_MOBILE = "mobile";
public static final String KEY_COMPANY = "company";
public static final String KEY_SPEAKERID = "speaker_id";
String s_id;
private EditText u_name;
private EditText u_email;
private EditText u_mobile;
private EditText u_company;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect_with_speaker);
linear_layoutcontainer = (LinearLayout) findViewById(R.id.linear_layoutcontainer);
toolbar = (Toolbar) findViewById(R.id.customtoolbar);
TextView title = (TextView) toolbar.findViewById(R.id.title);
title.setText("Connect with Speakers");
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
u_name = (EditText) findViewById(R.id.name);
u_email = (EditText) findViewById(R.id.email);
u_mobile = (EditText) findViewById(R.id.mobile);
u_company = (EditText) findViewById(R.id.compny_name);
submit = (Button) findViewById(R.id.connect);
submit.setOnClickListener(this);
s_id = getIntent().getStringExtra("speakerid");
}
private void submitdetails() {
final String name = u_name.getText().toString().trim(); //trim() remove spaces after&before string
final String email = u_email.getText().toString().trim();
final String mobile = u_mobile.getText().toString().trim();
final String company = u_company.getText().toString().trim();
final String speaker_id = s_id;
Toast.makeText(ConnectWithSpeaker.this, "submit details", Toast.LENGTH_SHORT).show();
CustomJSONObjectRequest request2 = new CustomJSONObjectRequest(Request.Method.POST, url, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Response........"+response);
if (response.trim().equals("success")) {
Toast.makeText(getApplicationContext(), "Your request is proceed, we will update you with further updates.",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ConnectWithSpeaker.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_NAME, name);
params.put(KEY_EMAIL, email);
params.put(KEY_MOBILE, mobile);
params.put(KEY_COMPANY, company);
params.put(KEY_SPEAKERID, speaker_id);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request2);
}
#Override
public void onClick(View v) {
if (v == submit) {
if (TextUtils.isEmpty(u_name.getText().toString())) {
u_name.setError("Enter Name");
u_name.requestFocus();
}
if (TextUtils.isEmpty(u_email.getText().toString())) {
u_email.setError("Enter Email");
u_email.requestFocus();
}
if ((TextUtils.isEmpty(u_mobile.getText().toString())) || (u_mobile.length() < 10 || u_mobile.length() > 15)) {
u_mobile.setError("Enter valid Mobile No");
u_mobile.requestFocus();
}
if (TextUtils.isEmpty(u_company.getText().toString())) {
u_company.setError("Enter Company Name");
u_company.requestFocus();
} else {
submitdetails();
}
}
}
This is the error in logcat.
E/Volley: [1515] BasicNetwork.performRequest: Unexpected response code 400 for http://
I am using this.
public class AEJsonRequest extends JsonObjectRequest {
private static int mStatusCode;
public AEJsonRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
ServerHandler.bwLog("sending params", jsonRequest.toString());
}
public AEJsonRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
public static int getStatusCode() {
return mStatusCode;
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
mStatusCode = volleyError.networkResponse.statusCode;
ServerHandler.bwLog("Error Status code", "" + mStatusCode);
VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
volleyError = error;
}
return volleyError;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded");
params.put("Accept", "application/json");
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
}
and call it to
public void submitDetail(HashMap<String, String> hashMap) throws JSONException {
//param is the JSONobject
final AEJsonRequest jsonRequest = new AEJsonRequest(Request.Method.POST, "url", new JSONObject(hashMap),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// if status is true, it will return the json data to its calling activity
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
MAX_TIMEOUT_MS,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Hope this'd help
In my Project if I add parameters with url and then make a request that is being received by the server. But if I use GET params method then the request is not being received by the server.
Successful request
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText name1=(EditText)findViewById(R.id.editText);
final EditText price1=(EditText)findViewById(R.id.editText2);
final EditText description1=(EditText)findViewById(R.id.editText3);
Button submit=(Button)findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onClick(View v) {
final String name=name1.getText().toString();
final double price= Double.parseDouble(price1.getText().toString());
final String description=description1.getText().toString();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://192.168.0.101/webservice/create_product.php?name=symphony&price=1000&description=from_android";
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Log.d("From Volley",+jo.getInt("success")+" "+jo.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("From Volley", error.getMessage());
}
});
Log.d("From Volley",sr.getUrl()+" "+sr.toString());
queue.add(sr);
}
});
}
}
Failed request
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText name1=(EditText)findViewById(R.id.editText);
final EditText price1=(EditText)findViewById(R.id.editText2);
final EditText description1=(EditText)findViewById(R.id.editText3);
Button submit=(Button)findViewById(R.id.button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
#Override
public void onClick(View v) {
final String name=name1.getText().toString();
final double price= Double.parseDouble(price1.getText().toString());
final String description=description1.getText().toString();
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url ="http://192.168.0.101/webservice/create_product.php";
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo=new JSONObject(response);
Log.d("From Volley",+jo.getInt("success")+" "+jo.getString("message"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("From Volley", error.getMessage());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("name",name);
params.put("price", String.valueOf(price));
params.put("description",description);
return params;
}
};
Log.d("From Volley",sr.getUrl()+" "+sr.toString());
queue.add(sr);
}
});
}
}
Here you use GET method that you have to build URL before make request, getParams() is used when request method is post...
Build URL for GET As follow
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("192.168.0.101")
.appendPath("webservice")
.appendPath("create_product.php")
.appendQueryParameter("name", name)
.appendQueryParameter("price", String.valueOf(price))
.appendQueryParameter("description", description);
String url = builder.build().toString();
StringRequest sr=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
}
change to
StringRequest sr=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
}
I want to access my Android apps through Web-Service.
but getting error in my android app ,
i am using volley & POST method for login.. `public class Main extends AppCompatActivity implements View.OnClickListener
{
public static final String LOGIN_URL = "http://10.54.103.8:4067/evivaservices/Webservices/login";
public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_layout);
editTextUsername = (EditText) findViewById(R.id.username1);
editTextPassword = (EditText) findViewById(R.id.password1);
buttonLogin = (Button) findViewById(R.id.login_button);
buttonLogin.setOnClickListener(this);
}
private void userLogin() {
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try
{
JSONObject jsonObject = new JSONObject(response);
Next();
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString(), Toast.LENGTH_LONG ).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_USERNAME,username);
map.put(KEY_PASSWORD,password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void Next(){
Intent intent = new Intent(this, HomeScreen.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
}
#Override
public void onClick(View v)
{
userLogin();
}
}
`
JSON DATA
{
"id": 31,
"username": "andrew.cope#services.co.in",
"user_image": "http:\/\/103.54.103.8:4067\/evivaservices\/img\/profile_31.png",
"err-code": 0
}
`
Please change your StringRequest to JsonRequest as below:
JsonRequest jsonRequest = new JsonRequest(Request.Method.POST, LOGIN_URL, new Response.Listener<>() {
#Override
public void onResponse(Object response) {
try {
Next();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
return map;
}
#Override
protected Response parseNetworkResponse(NetworkResponse response) {
return null;
}
#Override
public int compareTo(Object another) {
return 0;
}
};
Thank You.
Hello dear you made a mistake while you parsing the response
JSONArray jsonArray=jsonObject.getJSONArray("err-code")
remove above the line and then parse again.
In you JSON DATA, I not find array, so you shouldn't use JsonArray, you can delete this line in your code :JSONArray jsonArray=jsonObject.getJSONArray("err-code").