我们需要知道,Http协议是基于TCP协议的,而TCP协议是一种有连接,可靠的传输协议,如果丢失的话,会重传。所以这样的话,就不会有数据的丢失了。而Http协议有三种方法,Get,Post,Head方法,但是用的多的只有Get和Post方法,Get方法是将请求参数放在请求头中,所以请求的参数在URL中可见,而Post方法是将请求参数放在数据部分,所以在URL中不可见,Post相对来说保密,所以在提交重要信息的时候,用的都是HttpPost方法来实现的.
1.使用HttpGet请求Baidu的主页:
//使用HttpGet方法,把百度的主页传入
HttpGet hettpGet = new HttpGet("http://www.baidu.com/");
//使用默认的HttpClient
HttpClient hc = new DefaultHttpClient();
try {
//执行HttpGet方法,并且获取返回的响应
HttpResponse response = hc.execute(hettpGet);
//如果响应码为200则表示获取成功,否则为发生错误
if (response.getStatusLine().getStatusCode() == 200) {
//s就是获得的HTML代码
String s = EntityUtils.toString(response.getEntity());
System.out.println(s);
}
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{ e.printStackTrace();
//使用HttpPost发送请求
HttpPost httpPost = new HttpPost(url);
//使用NameValuePaira保存请求中所需要传入的参数
List<NameValuePair> paramas = new ArrayList<NameValuePair>();
paramas.add(new BasicNameValuePair("a", "a"));
try {
HttpResponse httpResponse;
//将NameValuePair放入HttpPost请求体中
httpPost.setEntity(new UrlEncodedFormEntity(paramas,HTTP.UTF_8));
//执行HttpPost请求
httpResponse = new DefaultHttpClient().execute(httpPost);
//如果响应码为200则表示获取成功,否则为发生错误
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String s = EntityUtils.toString(httpResponse .getEntity())}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}