简体   繁体   English

将字符串转换为列表<NameValuePair>

[英]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. 我基本上是想将List<NameValuePair>传递给处理Android应用上的POST HTTPRequest的外部类。

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 >. ASyncTask的doInBackgroud接收两个参数(请求的URL和nameValuePairs.toString()的结果),我找不到将字符串转换回List <NameValuePair>的方法。

Any ideas? 有任何想法吗?

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) 我为您提供了一个示例,说明如何通过POST或GET使用REST服务,将List <NameValuePair>设置为参数,然后将响应解析为一个字符串,然后该字符串可以用作您的对象(JSON,XML或数据框)

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

}

You can't, unless you write some sort of converter that pulls apart a known format, eg, nvp[0].name=xxx, nvp[0].value=zzz etc. or re-structures the default toString output (not fun). 除非您编写了某种分解已知格式的转换器,否则不能这样,例如, nvp[0].name=xxx, nvp[0].value=zzz等。或重新构造默认的toString输出(不是好玩)。

Normally you'd use JSON, XML, etc. instead of List.toString . 通常,您将使用JSON,XML等代替List.toString

Or use an actual HTTP client library. 或使用实际的HTTP客户端库。

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] 您可以看到输出类似于: [a=b, c=d]

so you can write a parser (or maybe using split() ) to restore the List. 因此您可以编写一个解析器(或使用split() )来还原列表。 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. 但是,我认为依靠ArrayList和NameValuePair中的toString的实现并使用另一种序列化方法(例如Dave所说的JSON)不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM