①.创建HttpClient对象: HttpClient httpClient = new DefaultHttpClient(); ②发送 GET 请求,创建 HttpGet 对象;发送 POST 请求,创建 HttpPost 对象。 ③设置请求参数:两者都可以用setParams(HttpParams);post 请求还可以用setEntity(HttpEntity)。 ④调用httpClient对象的execute()方法发送请求,会返回一个 HttpResponse。 ⑤对返回的HttpResponse调用,getEntity()方法可以获得HttpEntity对象,该对象包含了服务器响应内容。
另外,如果是带有参数的GET请求的话,我们可以将参数放到一个List集合中,再对参数进行URL编码, 最后和URL拼接下就好了:
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("user", "猪小弟")); params.add(new BasicNameValuePair("pawd", "123")); String param = URLEncodedUtils.format(params, "UTF-8"); HttpGet httpGet = new HttpGet("http://www.baidu.com"+"?"+param);POST请求比GET稍微复杂一点,创建完HttpPost对象后,通过NameValuePair集合来存储等待提交 的参数,并将参数传递到UrlEncodedFormEntity中,最后调用setEntity(entity)完成, HttpClient.execute(HttpPost)即可;
private void PostByHttpClient(final String url) { new Thread() { public void run() { try{ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user", "猪大哥")); params.add(new BasicNameValuePair("pawd", "123")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"UTF-8"); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity2 = httpResponse.getEntity(); detail = EntityUtils.toString(entity2, "utf-8"); handler.sendEmptyMessage(SHOW_DATA); } }catch(Exception e){e.printStackTrace();} }; }.start(); }转自:http://www.runoob.com/w3cnote/android-tutorial-httpclient.html
