您的位置:首页 > 理论基础 > 计算机网络

http post 方法传递参数的2种方式

2013-10-12 18:16 381 查看
try{
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(param);//param参数,可以为"key1=value1&key2=value2"的一串字符串
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);
String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
} catch(IOException e){
}


以android为例吧,有的时候我们不想要通过下面的方式来传递参数,因为考虑ndk的接口时我比较喜欢的方式是直接把key和value连成一串,如"key1=value1&key2=value2"来作为参数,这样http get和post的方法都可以用同样的结构来作为参数,于是http post的方法请求服务器数据时可以用上面的方法来实现.
List<NameValuePair>list = new ArrayList<NameValuePair>();
for (int i = 0; i < keys.length; i++) {
list.add(new BasicNameValuePair(keys[i], values[i]));
}
HttpPost httpRequst = new HttpPost(urlString);
httpRequst.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));


httpRequst.setEntity()这个方法是最主要的post传递的参数实现的方式了(不知道这样说对不对)

httpEntity有AbstractHttpEntity, BasicHttpEntity, BasicManagedEntity, BufferedHttpEntity, ByteArrayEntity, EntityTemplate, FileEntity, HttpEntityWrapper, InputStreamEntity,SerializableEntity, StringEntity, UrlEncodedFormEntity
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: