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

2023-10-29

     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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

http post 方法传递参数的2种方式 的相关文章