3、基本的Get和Post访问

Get方式访问

HttpClient hc = new DefaultHttpClient();

		

HttpUriRequest request = new HttpGet("http://www.baidu.com?wd=HttpClient");

		

HttpResponse hr = hc.execute(request);

		

String body = EntityUtils.toString(hr.getEntity());

		

System.out.println(body);

Post方式访问

DefaultHttpClient hc = new DefaultHttpClient();

hc.setRedirectStrategy(new LaxRedirectStrategy());  //如果有跳转,就返回跳转后的内容

		

HttpPost hp = new HttpPost("http://www.baidu.com?wd=HttpClient");

		

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("username", "angelshelter"));

params.add(new BasicNameValuePair("keyword", "123"));

		

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");

hp.setEntity(entity);

		

HttpResponse hr = hc.execute(hp);

		

String body = EntityUtils.toString(hr.getEntity());

		

System.out.println(body);

  

你可能感兴趣的:(post)