http post 方法傳遞引數的2種方式
阿新 • • 發佈:2019-01-08
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傳遞的引數實現的方式了(不知道這樣說對不對)