6

I have been trying to send data to server through GET method but I am unable to find a way to do it. I have tried few codes in asynchronous task but nothing. The web services are made in cakePhp and the format is like this:

Base_URI/users/add.json?json={“email”: xxx@x.com, “password”: “xxxxxxxxx”, “first_name”: “Xyz”, “last_name”: “Xyz”}

Android experts are requested to figure a way out of this problem. Thanks

Here is the code:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("email", UserDummy.email));
            nameValuePairs.add(new BasicNameValuePair("password", UserDummy.password));
            nameValuePairs.add(new BasicNameValuePair("first_name", UserDummy.fname));
            nameValuePairs.add(new BasicNameValuePair("last_name", UserDummy.lname));
            // 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));

            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, HTTP.UTF_8);
            url += "?json={" + paramString+"}";                                                                                                                                                     ;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        Log.v("XXX", e.getMessage());
    }

    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;

HttpGet is not accepting this format of url and is giving the error but when I try it on browser it works fine. Error is following:

Illegal character in query at index 56
Shahzeb
  • 3,696
  • 4
  • 28
  • 47
  • 1
    post your code,...we'll help fix it – petey Jan 18 '14 at 19:40
  • 1
    Are you sure you should be using a JSON as a GET parameter; what's wrong with normal name-value pairs. Also, you'd need to encode that JSON to base64 and lastly, i believe there's a 255 character limit on GET request but don't quote me on that. – W.K.S Jan 18 '14 at 19:44
  • Also, I dunno if you've developed the server implementation, but it's best not to send email and password over a GET request. Encrypting both parameters and POSTing them is a more secure approach. – W.K.S Jan 18 '14 at 19:47
  • The request being executed here is a `POST` request not a `GET` request. Are you sure this is what you want ? – Halim Qarroum Jan 18 '14 at 20:02
  • @Halim No, I know I would have to use namevaluepairs, but don't know how – Shahzeb Jan 18 '14 at 20:28
  • @Shahzeb Why don't you use a `HttpGet` request instead, and use a name value pair (from your example `json`/your_actual_json_serialized_object) ? – Halim Qarroum Jan 18 '14 at 20:40
  • that is what I am asking. I mean how ? – Shahzeb Jan 18 '14 at 21:13
  • Just switch your `HttpPost` to a `HttpGet`. Then you'd need to build a `BasicNameValuePair` just as you did in your example, having a key corresponding to "json" and a value corresponding to the string serialized representation of your `UserDummy` object (an example of how to do this here http://stackoverflow.com/questions/5571092/convert-object-to-json-in-android). – Halim Qarroum Jan 18 '14 at 23:21
  • Actually I am stuck on '=' sign. Its giving me error because of this part "?json={}" – Shahzeb Jan 19 '14 at 08:00
  • @Halim please have a look on my code and tell me what to do. Thanks – Shahzeb Jan 19 '14 at 08:04
  • This is the error in the logcat: 01-19 05:06:25.531: V/XXX(1182): Illegal character in query at index 56 – Shahzeb Jan 19 '14 at 10:07
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/45570/discussion-between-shahzeb-and-halim-qarroum) – Shahzeb Jan 19 '14 at 10:15
  • BTW, you can get the respone string from Entity by using: `String response = EntityUtils.toString(response.getEntity);`. – W.K.S Jan 19 '14 at 10:25

4 Answers4

3

Finally after debugging and trying different solutions the whole day, I solved the problem :)

I needed to encode the parameters part and not the whole URL like this:

String url = "Base_URI/users/add.json?json=";
    url =url +  URLEncoder.encode("{\"email\":\""+email+"\",\"password\":\""+password+"\"}", "UTF-8");

Thanks everyone for your support !

Shahzeb
  • 3,696
  • 4
  • 28
  • 47
0

Use volley lib for networking in android.

Sergey Sheleg
  • 720
  • 6
  • 6
  • 1
    There is no need to use any third party library here. Android comes with the `org.apache.http` package built-in which already has everything needed in order to do what the OP wants. – Halim Qarroum Jan 18 '14 at 20:56
  • Volley is more up to date networking in android. And it very simple – Sergey Sheleg Jan 19 '14 at 12:14
  • Maybe, but it adds unnecessary heavyness in your app as you could use the built-in method, which is not really complicated to use compared to what the OP wants. – Halim Qarroum Jan 19 '14 at 12:26
  • tried volley library too but this is too not getting url format. – Shahzeb Jan 19 '14 at 17:25
0

Your string comparisons are not right.

This compares object references and will not work for you:

method == "POST"

Intead, use equals():

"POST".equals(method);

You can also do:

method.equals("POST");

but that may cause an error if method is null.

MikeHelland
  • 1,151
  • 1
  • 7
  • 17
  • This isn't the issue. Its working perfectly fine. The issue here is parsing json from given url by GET method – Shahzeb Jan 19 '14 at 09:06
  • According to the code you posted, "is" will be null. It will never be set. No HTTP method will be chosen. The error logs in your other message confirm that. If there is a problem parsing, it is because you are parsing null. – MikeHelland Jan 19 '14 at 09:10
0

If you want to use method GET:

This method may help you

/**
 * 
 * @param url stands for API
 * @param 
 *      params[i][0] stands for column's name
 *      params[i][1] stands for value which respective with column's name
 * @return InputStream which got from Server
 */
public static int sendJSONObject(IGetUserData iUserId, String method, String url, String[]... params) {
    InputStream mInputStream = null;
    HttpClient mHttpClient = null;
    HttpRequestWithEntity mHttpGet = null;
    int status = Def.REQUEST_INVALID;
    try {
        mHttpClient = new DefaultHttpClient();

        mHttpGet = new HttpRequestWithEntity(url, method);

        JSONObject mObject = new JSONObject();
        for (String[] pair : params) {
            mObject.put(pair[0], pair[1]);
        }

        StringEntity mStringEntity = new StringEntity(mObject.toString());
        mStringEntity.setContentEncoding("UTF-8");
        mStringEntity.setContentType("application/json");

        mHttpGet.setEntity(mStringEntity);          
        HttpResponse mResponse = mHttpClient.execute(mHttpGet);
        status = mResponse.getStatusLine().getStatusCode();

        Log.d(TAG, "status: " + status);
        if (mResponse != null && 
                (status == Def.CREATED || status == Def.OK)) {
            mInputStream = mResponse.getEntity().getContent();  
            if(mInputStream != null){
                String json = StreamUtils.converStreamToString(mInputStream);
                userId = JSONUtils.getUserId(json);
                iUserId.sendUserId(userId);
                Log.d("viet","userid = " + userId);
            }
        }

    } catch (Exception e) {
        Log.e(TAG, "Error during send");
        status = Def.NETWORK_ERROR;
    }
    return status;
}

Right here is what you need.

    mHttpClient = new DefaultHttpClient();

    mHttpGet = new HttpRequestWithEntity(url, method);

    JSONObject mObject = new JSONObject();
    for (String[] pair : params) {
        mObject.put(pair[0], pair[1]);
    }

    StringEntity mStringEntity = new StringEntity(mObject.toString());
    mStringEntity.setContentEncoding("UTF-8");
    mStringEntity.setContentType("application/json");

    mHttpGet.setEntity(mStringEntity);          
    HttpResponse mResponse = mHttpClient.execute(mHttpGet);

And here is HttpRequestWithEntity.java

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

public class HttpRequestWithEntity extends HttpEntityEnclosingRequestBase {

    private String method;

    public HttpRequestWithEntity(String url, String method) {
        if (method == null || (method != null && method.isEmpty())) {
            this.method = HttpMethod.GET;
        } else {
            this.method = method;
        }
        try {
            setURI(new URI(url));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getMethod() {
        return this.method;
    }

}
Luc
  • 2,800
  • 2
  • 25
  • 46