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


 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){ }

有的时候我们不想要通过下面的方式来传递参数,因为考虑请求接口时我比较喜欢的方式是直接把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, BasticHttpEntity, BasicManageEntity, BufferedHttpEntity, ByteArrayEntity, EntityTemplate,  FileEntity, HttpEntityWrapper, InputStreamEntity, SerializableEntityStringEntityUrlEncodedFormEntity

转载:https://blog.csdn.net/yuleran/article/details/12655493


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM