LIst<NameValuePair> 转换为以&分隔的字符串
时间: 2023-04-02 20:01:28 浏览: 71
问:LIst<NameValuePair> 转换为以 & 分隔的字符串,应该怎么做?
回答:可以使用 Apache 的 HttpClient 库中的 URLEncodedUtils 工具类,调用其中的 format 方法即可将 LIst<NameValuePair> 转换为以 & 分隔的字符串。
相关问题
httpclient post 传递List<String>
可以使用以下代码进行HttpPost传递List<String>:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
List<String> list = new ArrayList<>();
list.add("string1");
list.add("string2");
for (String s : list) {
params.add(new BasicNameValuePair("key[]", s));
}
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
```
其中,将List<String>转化为List<NameValuePair>,并以"key[]"的形式添加到请求参数中。
protected String doInBackground(String... args) { String name1 = name.getText().toString(); String password1 = password.getText().toString(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name1)); params.add(new BasicNameValuePair("password", password1)); try{ JSONObject json = jsonParser.makeHttpRequest(url, "POST", params); String message = json.getString(TAG_MESSAGE); return message; }catch(Exception e){ e.printStackTrace(); return ""; } }
这段代码看起来像是 Android 应用程序中的异步任务(AsyncTask)的 doInBackground() 方法,它通过 HTTP POST 请求发送了一个名为 url 的地址,并传递了两个参数:name 和 password。在 try 块中,它通过 JSON 解析器将响应转换为一个 JSONObject 对象,并从中获取了一个名为 TAG_MESSAGE 的属性值。最后,它返回了这个属性值作为 doInBackground() 方法的结果。在处理异常时,它打印了异常堆栈,并返回了一个空字符串。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)