0

Does Android Volley do URL Encoding?

I am trying to do a Get Request and on server side, it seems the URL being sent through is not encoded correctly.

I have been fiddling with my CustomRequest class but am not able to get it working, if it does encoding.

CustomRequest.java:

package com.bidorbuy.app.network;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request; 
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;


public class CustomRequest extends Request<JSONObject> {

private Response.Listener<JSONObject> listener;
private Map<String, String> params;
private Map<String, String> headers;
Priority priority;

public CustomRequest(String url,
                     Map<String, String> params,
                     Map<String, String> headers,
                     Response.Listener<JSONObject> reponseListener,
                     Response.ErrorListener errorListener,
                     Priority priority)
{
    super(Method.GET, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    this.headers = headers;
    this.priority = priority;
}

public CustomRequest(int method,
                     String url,
                     Map<String, String> params,
                     Map<String, String> headers,
                     Response.Listener<JSONObject> reponseListener,
                     Response.ErrorListener errorListener,
                     Priority priority) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    this.headers = headers;
    this.priority = priority;
}

protected Map<String, String> getParams()
        throws com.android.volley.AuthFailureError {
    return params;
};

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers;
}

@Override
public byte[] getBody() throws AuthFailureError {
    Map<String, String> params = getParams();
    if(params!=null && params.size() > 0){
        return encodeParameters(params, getParamsEncoding());
    }
    return null;
}

private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
    StringBuilder encodedParams = new StringBuilder();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
            encodedParams.append('=');
            encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            encodedParams.append('&');
        }
        return encodedParams.toString().getBytes(paramsEncoding);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
    }
}

@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));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}


}

and then I use the request elsewhere in the app as seen below:

    public void getRequest(String url, Map<String, String> params, final String source) {

    getHeaders(headers);

    CustomRequest jsObjRequest = new CustomRequest(Request.Method.GET, url, params, headers, getReponse(source), createMyReqErrorListener(), Constants.PRIORITY_HIGH);
    queue.add(jsObjRequest);

}

and this is the code i am passing the params through to be used in the network call:

    private void forgotPasswordExecute() {
    forgotPasswordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Map<String, String> params = new HashMap<String, String>();
            LocalBroadcastManager.getInstance(ForgotPasswordActivity.this).registerReceiver(forgotPasswordReceiver, new IntentFilter(Constants.WS_FORGOT_PASSWORD));
            params.put("emailAddress", "some@email.com");


            String url = Constants.FORGOT_PASSWORD_URL;
            request.getRequest(url, params, "ForgotPassword");
            System.out.println("URL is: " + url);
        }
    });
}

I just need some assistance with the encoding of the URL in volley. If volley does not do it, is there another way i could encode the URL and still use Volley?

Thanks

Stillie
  • 2,647
  • 6
  • 28
  • 50
  • 1
    IMO, you can find a solution at [Volley - POST/GET parameters](http://stackoverflow.com/questions/16626032/volley-post-get-parameters). Pay attention to @Ogre_BGR's and LOG_TAG's answers. Hope this helps! – BNK Aug 26 '15 at 02:00

1 Answers1

1

Try this , (may be not the best approach) Direct code which I used in my project. Late answer after 1 year , may be usefull for future visitors..

public void yourMethodName() {

    StringRequest request = new StringRequest(Request.Method.GET, link , new Response.Listener<String>() {
        @Override
        public void onResponse(String result) {
            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONArray jsonArray = jsonObj.getJSONArray("data");

                // Do something here

            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(),"check connection , or try again later",Toast.LENGTH_SHORT).show();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    }){
        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            try {
//                    String utf8String = new String(response.data, "UTF-8");
                String data = URLEncoder.encode("param", "UTF-8") +     "=" + URLEncoder.encode("param", "UTF-8");
                URL url = new URL(link);
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line;
                while ((line = br.readLine()) != null)
                    sb.append(line);
                br.close();
                return Response.success(new String(sb.toString()), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (Exception e) {
                return Response.error(new ParseError(e));
            }
        }
    };


    queue.add(request);

}
Omar Dhanish
  • 885
  • 7
  • 18