Hito_kun
Hito_kun

Reputation: 992

Cast String to List<NameValuePair>

I'm basically trying to pass a List<NameValuePair> to an external class that handles POST HTTPRequest on an Android app.

String[] args = new String[]{"http://url/login", nameValuePairs.toString()}; //nameValuePairs is a param list to send via POST
        Log.i("params", nameValuePairs.toString());
        try {
            String text = new rest().execute(args).get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The doInBackgroud of the ASyncTask receives two parameters (the url for the request and the result of nameValuePairs.toString()), and I cannot find a way to convert the string back to a List< NameValuePair >.

Any ideas?

Upvotes: 1

Views: 10775

Answers (3)

eltabo
eltabo

Reputation: 3807

If you execute a code like this:

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

....

List<NameValuePair> h = new ArrayList<NameValuePair>();
h.add(new BasicNameValuePair("a", "b"));
h.add(new BasicNameValuePair("c", "d"));

Log.d("jj", h.toString());

you can see that the output is something like: [a=b, c=d]

so you can write a parser (or maybe using split()) to restore the List. However I think it's not a good idea to rely on the implementation of toString in ArrayList and NameValuePair, and use another kind of serialization method, like JSON as Dave said.

Upvotes: 1

I bring you an example of how to consume REST services by POST or GET, sets the List< NameValuePair > as parameters and then parse the response to a string that can then be used as suits you (JSON, XML, or a data frame)

import java.io.*;
import java.util.*;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.*;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.*;
import org.apache.http.impl.client.*;
import org.apache.http.message.*;

public class RESTHelper {

private static final String URL_POST = "http://url/login";
private static final String URL_GET = "http://url/login";

public static String connectPost(List<BasicNameValuePair> params){
    String result = "";
    try{
        HttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(URL_POST);

        request.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse response = client.execute(request);

        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
        }
    }catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

public static String connectGet(List<BasicNameValuePair> params){
    String result = "";
    try{
        String finalUrl = URL_GET + URLEncodedUtils.format(params, null);

        HttpClient client = new DefaultHttpClient();

        HttpGet request = new HttpGet(finalUrl);

        HttpResponse response = client.execute(request);

        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
        }
    }catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder(); 
    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

Upvotes: 3

Dave Newton
Dave Newton

Reputation: 160191

You can't, unless you write some sort of converter that pulls apart a known format, e.g., nvp[0].name=xxx, nvp[0].value=zzz etc. or re-structures the default toString output (not fun).

Normally you'd use JSON, XML, etc. instead of List.toString.

Or use an actual HTTP client library.

Upvotes: 1

Related Questions