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, SerializableEntity, StringEntity, UrlEncodedFormEntity
轉載:https://blog.csdn.net/yuleran/article/details/12655493