Creating an AsyncTask to work with 3 layers? - android

In my project I am use 3 layers: Activity, DAO and Web Service Transaction, layer Web Service Transaction has HttpClient to execute Get and Post in my web service.
An example to understand:
//structure
send: Activity->DAO->WebService
response: WebService->DAO->Activity
These works, but I'm using Threads and I don't want to use anymore threads. I want knows if there any way to create a generic AsyncTask that can return Boolean and List ?
Looking for a solution I founded this: Want to create a Generic AsyncTask but doesn't work to me, or I can't understand how this works.
How can I do to AsyncTask works in 3 layers as my project ?
So, here my real structure;
Activity
public class MainActivity extends ActionBarActivity {
private EditText login, senha;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(android.os.Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy pol = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(pol);
}
login = (EditText)findViewById(R.id.usuario);
senha = (EditText)findViewById(R.id.senha);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//invoke methods of UsuarioDAO
}
});
}
}
DAO
public class UsuarioDAO{
private HttpClientTransaction httpClient;
/** constructor */
public UsuarioDAO() {
httpClient = new HttpClientTransaction();
}
/** insert new object */
public Boolean insert(Usuario u){
boolean insert = false;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "add"));
nameValuePairs.add(new BasicNameValuePair("nome", u.getNome()));
nameValuePairs.add(new BasicNameValuePair("login", u.getLogin()));
nameValuePairs.add(new BasicNameValuePair("senha", u.getSenha()));
String s = "http://192.168.1.102/android/login.php";
String response = httpClient.post(nameValuePairs, s);
try {
JSONObject obj = new JSONObject(response);
if(obj.getString("erro").equals("1")){
insert = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return insert;
}
/** check if usuario has login */
public Boolean isLogin(Usuario u){
boolean login = false;
String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
String response = httpClient.get(s);
try {
JSONObject obj = new JSONObject(response);
if(obj.getString("erro").equals("1")){
login = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return login;
}
/** return a list with all usuarios */
public List<Usuario> getAllUsuario(){
List<Usuario> list = new ArrayList<Usuario>();
String s = "http://192.168.1.102/android/login.php?action=getAll";
String response = httpClient.get(s);
try {
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.getJSONArray("all");
for(int x = 0; x < jsArray.length(); x++){
JSONObject objArray = jsArray.getJSONObject(x);
Usuario u = new Usuario();
u.setNome(objArray.getString("nome"));
u.setLogin(objArray.getString("login"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}
Web Service Transaction
public class HttpClientTransaction {
private static HttpClient httpClient;
public HttpClientTransaction() {
httpClient = HttpClientConnection.getHttpClient();
}
/** execute POST */
public String post(List<NameValuePair> list, String url){
String s = "";
try {
HttpPost httpPost = new HttpPost(url);
//httpPost.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
s = EntityUtils.toString(entity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return s;
}
/** execute GET */
public String get(String url){
String s = "";
try {
//executa o get
HttpGet httpGet = new HttpGet(url);
//httpGet.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
s = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}

To my problem I resolved use Volley Library and now works.
I did this
Volley Singleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Application Controller
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
//Construtores
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
//método requerido.
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
//método requerido.
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
//método requerido
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
UsuarioDAO
public class UsuarioDAO{
private String url = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
/** constructor */
public UsuarioDAO() {
}
public static ApplicationController isLogin(Usuario u, final UsuarioImp usuarioImp){
String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
ApplicationController app = new ApplicationController(s,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("erro").equals("1")){
Usuario u = new Usuario();
u.setNome("Fernando Paiva - Logado");
usuarioImp.onLoginSuccess(u);
}else{
usuarioImp.onLoginFailure("Erro de login");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
//usuarioImp.onLoginFailure("erro de login");
}
});
return app;
}
Usuario Interface
public interface UsuarioImp {
public void onLoginSuccess(Usuario u);
public void onLoginFailure(String message);
}
Activity
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ApplicationController app = UsuarioDAO.isLogin(new Usuario(), new UsuarioImp() {
#Override
public void onLoginSuccess(Usuario u) {
Log.i("USUARIO NOME: ", u.getNome());
}
#Override
public void onLoginFailure(String message) {
Log.i("ERROOOO: ", message);
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
CustomVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
});

Related

How to I send POST parameters in this android studio code [duplicate]

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 5 years ago.
I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:
public class BGTask extends AsyncTask<String, String, String > {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
String color = "null";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//I want to pass the id parameter
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
int status = parentObject.getInt("status");
if(status == 1) {
color = parentObject.getString("bgcolor");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return color;
}
}
The variable color is in hex code i.e #FF0089
** Use volley library for GET , POST and network calls it's very simple and efficient **
First create AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Second make POST request
public void Send() {
final String First = "";
final String Second = "";
StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
if (success.equals("")) {
Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_FIRST_PARAMETERS, First);
params.put(KEY_SECOND_PARAMETER, Second);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Include volley library
compile 'com.android.volley:volley:1.0.0'
Don't forget to add android:name=".AppController" in application tag of manifest file

How to put Cookie session id into volley request?

So, i have this code to make a POST request with volley:
public class MainActivity extends AppCompatActivity {
Button btnSearch;
ProgressDialog loadingDialog;
ListView lvResult;
String session_id;
RequestQueue queue;
MyCookieManager myCookieManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch = (Button) findViewById(R.id.btnSearch);
lvResult = (ListView) findViewById(R.id.lvResult);
loadingDialog = new ProgressDialog(MainActivity.this);
loadingDialog.setMessage("Wait.\nLoading...");
loadingDialog.setCancelable(false);
myCookieManager = new MyCookieManager();
requestCookie(); //FIRST CALL TO GET SESSION ID
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showLoading();
requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
}
});
}
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener < String > () {
#Override
public void onResponse(String response) {
//
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map < String, String > getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap < String, String > ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
//"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
return params;
}
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(postRequest);
}
public void requestWithSomeHttpHeaders() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/json/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
Log.d("Response", response);
String x = myCookieManager.getCookieValue();
String status = "";
try {
JSONObject resultObject = new JSONObject(response);
Log.d("JSON RESULT =>", resultObject.toString());
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
hideLoading();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
#Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "param1=XPTO&param2=XPTO";
return httpPostBody.getBytes();
}
#Override
public Map <String, String> getHeaders() throws AuthFailureError {
Map <String, String> params = new HashMap <String, String> ();
params.put("User-Agent", "Mozilla/5.0");
params.put("Accept", "application/json, text/javascript, */*; q=0.01");
params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
return params;
}
};
queue.add(postRequest);
}
private void showLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!loadingDialog.isShowing())
loadingDialog.show();
}
});
}
private void hideLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
});
}
}
If I send a valid cookie ID this return a valid JSON object else a empty object.
I tried (unsuccessfully) to set default cookie handles like
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
but I get a empty object.
How to put a valid cookie session ID to post request?
So the problem was getting a valid cookie. My mistake was to get it from the POST request itself. I kept the same working principle, getting the cookie when I started the application but using GET instead of POST and calling the root of the URL instead of the address where I get the JSON.
My solution looked like this:
public void requestCookie() {
queue = Volley.newRequestQueue(this);
String url = "http://myurl.com/";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener <String> () {
#Override
public void onResponse(String response) {
String x = myCookieManager.getCookieValue();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error => " + error.toString());
hideLoading();
}
}
) {
protected Response <String> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
String header_response = String.valueOf(response.headers.values());
int index1 = header_response.indexOf("PHPSESSID=");
int index2 = header_response.indexOf("; path");
//Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
session_id = header_response.substring(index1, index2);
return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
queue.add(getRequest);
}
Using cookies with Android volley library
Request class:
public class StringRequest extends com.android.volley.toolbox.StringRequest {
private final Map<String, String> _params;
/**
* #param method
* #param url
* #param params
* A {#link HashMap} to post with the request. Null is allowed
* and indicates no parameters will be posted along with request.
* #param listener
* #param errorListener
*/
public StringRequest(int method, String url, Map<String, String> params, Listener<String> listener,
ErrorListener errorListener) {
super(method, url, listener, errorListener);
_params = params;
}
#Override
protected Map<String, String> getParams() {
return _params;
}
/* (non-Javadoc)
* #see com.android.volley.toolbox.StringRequest#parseNetworkResponse(com.android.volley.NetworkResponse)
*/
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
MyApp.get().checkSessionCookie(response.headers);
return super.parseNetworkResponse(response);
}
/* (non-Javadoc)
* #see com.android.volley.Request#getHeaders()
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
MyApp.get().addSessionCookie(headers);
return headers;
}
}
MyApp:
public class MyApp extends Application {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
private static MyApp _instance;
private RequestQueue _requestQueue;
private SharedPreferences _preferences;
public static MyApp get() {
return _instance;
}
#Override
public void onCreate() {
super.onCreate();
_instance = this;
_preferences = PreferenceManager.getDefaultSharedPreferences(this);
_requestQueue = Volley.newRequestQueue(this);
}
public RequestQueue getRequestQueue() {
return _requestQueue;
}
/**
* Checks the response headers for session cookie and saves it
* if it finds it.
* #param headers Response Headers.
*/
public final void checkSessionCookie(Map<String, String> headers) {
if (headers.containsKey(SET_COOKIE_KEY)
&& headers.get(SET_COOKIE_KEY).startsWith(SESSION_COOKIE)) {
String cookie = headers.get(SET_COOKIE_KEY);
if (cookie.length() > 0) {
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
cookie = splitSessionId[1];
Editor prefEditor = _preferences.edit();
prefEditor.putString(SESSION_COOKIE, cookie);
prefEditor.commit();
}
}
}
/**
* Adds session cookie to headers if exists.
* #param headers
*/
public final void addSessionCookie(Map<String, String> headers) {
String sessionId = _preferences.getString(SESSION_COOKIE, "");
if (sessionId.length() > 0) {
StringBuilder builder = new StringBuilder();
builder.append(SESSION_COOKIE);
builder.append("=");
builder.append(sessionId);
if (headers.containsKey(COOKIE_KEY)) {
builder.append("; ");
builder.append(headers.get(COOKIE_KEY));
}
headers.put(COOKIE_KEY, builder.toString());
}
}
}
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.
for getting cookie from login request
CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
new Response.Listener<CustomStringRequest.ResponseM>() {
#Override
public void onResponse(CustomStringRequest.ResponseM result) {
CookieManager cookieManage = new CookieManager();
CookieHandler.setDefault(cookieManage);
progressDialog.hide();
try {
//From here you will get headers
String sessionId = result.headers.get("Set-Cookie");
String responseString = result.response;
Log.e("session", sessionId);
Log.e("responseString", responseString);
JSONObject object = new JSONObject(responseString);
CustomStringRequest class
public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {
private Response.Listener<CustomStringRequest.ResponseM> mListener;
public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
super(method, url, listener);
this.mListener = responseListener;
}
#Override
protected void deliverResponse(ResponseM response) {
this.mListener.onResponse(response);
}
#Override
protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
ResponseM responseM = new ResponseM();
responseM.headers = response.headers;
responseM.response = parsed;
return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
}
public static class ResponseM {
public Map<String, String> headers;
public String response;
}
}
set cookie when add request to server..
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String session=sharedPreferences.getString("sessionId","");
headers.put("Cookie",session);
return headers;
}

Multipart request using volley returning null as response

Hi I am relatively new to android, I have used multipart request to upload an image to server using volley. The image is being uploaded correctly but I am getting the response as null. I checked on postman, I am strangely getting the correct response there.
MultipartRequest.java
public class MultipartRequest extends Request<JSONObject> {
private static final String FILE_PART_NAME = "user[avatar]";
private long cacheTimeToLive = 0;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<JSONObject> mListener;
private final File mImageFile;
protected Map<String, String> headers;
public MultipartRequest(String url, File imageFile, Listener<JSONObject> listener, ErrorListener errorListener){
super(Method.PUT, url,errorListener);
mListener = listener;
mImageFile = imageFile;
buildMultipartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void buildMultipartEntity(){
mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
JSONObject result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
uploadImage method :-
private void uploadImage(final Bitmap bitmap){
String name = "DP_"+ userName +".jpeg";
try {
file=bitmapToFile(name,bitmap);
} catch (IOException e) {
e.printStackTrace();
}
MultipartRequest jsonRequest = new MultipartRequest( UPLOAD_URL,
file,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,response.toString());
try {
// parseUserPhotoResponse(response);
Picasso.with(getApplicationContext())
.load(destination)
.placeholder(R.mipmap.placeholder)
.resize(avatarSize, avatarSize)
.centerCrop()
.transform(new CircleTransformation())
.into(ivUserProfilePhoto);
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Error: " + volleyError.getMessage());
if(volleyError!=null)
{
try {
NetworkResponse networkResponse = volleyError.networkResponse;
if (networkResponse != null) {
String responseBody = new String(volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
Log.d(TAG, "Response body" + responseBody.toString());
Log.d(TAG, jsonObject.toString());
if (jsonObject.getBoolean("error") == false) {
} else {
Toast.makeText(getApplicationContext(), "" + jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
//Handle a malformed json response
} catch (UnsupportedEncodingException error) {
}
}
}
})
;
//Creating a Request Queue
jsonRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(jsonRequest, "UPLOAD_IMAGE");
}

posting data to server in json format using volley

Hello i am posting data to server in json format,
but it returns volley server error in error response`
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#OveRequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}rride
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
return params;
}
};
queue.add(sr);`
Have a singleton which handles the request queue.
public class VolleySingleton {
// Singleton object...
private static VolleySingleton instance;
final private RequestQueue requestQueue;
private static ImageLoader imageLoader;
//Constructor...
private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(100000000);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
// Singleton method...
public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue(Context context) {
if (requestQueue != null) {
return requestQueue;
} else {
getInstance(context);
return requestQueue;
}
}
private RequestQueue getRequestQueue() {
return requestQueue;
}
public static ImageLoader getImageLoader(Context context) {
if (imageLoader != null) {
return imageLoader;
} else {
getInstance(context);
return imageLoader;
}
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag("App");
getRequestQueue().add(req);
}
}
Then using the below method you can send the request.
public void postVolley(final Context context, String url, JSONObject jsonObject) {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseJson) {
Log.e("success", "" + responseJson.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "" + error);
}
}) {
/**
* Setting the content type
*/
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjReq);
}
This works fine for me.

Volley JsonObjectRequest sending 3 JSONObject in same request?

I created a JsonObjectRequest that I use to send a JSONObject to my WebService. When I try send this JSONObject the object is sending but send 3 objects instead 1. Looking in my data base there's 3 objects added.
I can't understand why this problem, because I always send 1 JSONObject but in webservice there's 3 objects.
I tried to use Postman of Google Chrome, and using Postman send 1 JSONObject normally.
What can be ?
JsonObjectRequest
public JsonObjectRequest sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa,
final ContatoAdapter listener){
urlPost.append(WebServiceURL.getBaseWebServiceURL());
urlPost.append("/ws/contatos/contatos/add.json");
JSONObject jsObject = new JSONObject();
try {
JSONObject objs = new JSONObject();
objs.put("nome", nome);
objs.put("email", email);
objs.put("telefone", telefone);
objs.put("assunto", assunto);
objs.put("mensagem", mensagem);
objs.put("pessoa_id", idEmpresa);
jsObject.put("Contato", objs);
Log.i("JSONOBJECT->", jsObject.toString());
}catch(JSONException e){
Log.e("JSONException->", e.getLocalizedMessage());
}
Log.i("URL CONTATO EMPRESA->", urlPost.toString());
JsonObjectRequest apc = new JsonObjectRequest(Request.Method.POST,
urlPost.toString(),
jsObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
Log.i("JSOBJECT->", jsonObject.toString());
if(jsonObject.getString("status").equals("999")){
listener.isSend(true);
}else{
listener.isSend(false);
}
} catch (JSONException e) {
Log.e("JSONException->", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ERROR METHOD:", "sendContatoToEmpresa in ContatoDAO: " + volleyError.getLocalizedMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = new String(android.util.Base64.encode((BasicAuthenticationRest.USERNAME + ":" + BasicAuthenticationRest.PASSWORD).getBytes(), android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP));
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + auth);
return headers;
}
};
return apc;
}
Activity
public Integer sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa){
final int[] send = {0};
if(nome.length() == 0 ||
email.length() == 0 ||
telefone.length() == 0 ||
assunto.length() == 0 ||
mensagem.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
send[0] = 0;
}else{
final ProgressDialog progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
JsonObjectRequest app = new ContatoDAO().sendContatoToEmpresa(nome,
email,
telefone,
assunto,
mensagem,
idEmpresa,
new ContatoAdapter(){
#Override
public void isSend(Boolean value) {
if(value){
send[0] = 1;
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
return send[0];
}
CustomVolleySingleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try to do the following:
app.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Here you can change the timeout (MY_SOCKET_TIMEOUT_MS) and change the number of attempts (DefaultRetryPolicy.DEFAULT_MAX_RETRIES)

Categories

Resources