* 步骤:
1. 建立HttpClient对象
2. 建立HttpGet或者HttpPost对象。将地址传给构造方法。
3. 让HttpClient对象执行请求。获得响应对象HttpResponse
4. 从HttpResponse对象中获得响应码。
5. 判断响应码是否为200,若是200则得到HttpEntity.
6. 用EntityUtils将数据从HttpEntity中得到数组
//http://localhost:8080/MyServer/login?username=admin&userpwd=111
String path = "http://localhost:8080/MyServer/login"; //1:建立HttpClient
HttpClient client = new DefaultHttpClient(); //2:建立请求。
HttpPost post = new HttpPost(path); //将数据封装到post对象里。 //建立一个存储封装键值对对象的集合
List<NameValuePair> params = new ArrayList<NameValuePair>(); //将数据封装到NameValuePair对象里,第一个参数为键,第二个参数为值
NameValuePair value1 = new BasicNameValuePair("username", "admin"); NameValuePair value2 = new BasicNameValuePair("userpwd", "1112"); //将对象添加到集合中。
params.add(value1); params.add(value2); //将数据集合封装成HttpEntity
HttpEntity entity = new UrlEncodedFormEntity(params); //设置HttpEntity
post.setEntity(entity); //让客户端执行请求。
HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if(code==200){ HttpEntity result_entity = response.getEntity(); String str = EntityUtils.toString(result_entity); System.out.println(str); }
//建立HttpClient对象--客户端
HttpClient client = new DefaultHttpClient(); //建立请求。---Get:HttpGet
String path = "http://a3.att.hudong.com/36/11/300001378293131694113168235_950.jpg"; HttpGet get = new HttpGet(path); //让客户端执行请求。获得响应对象
try { HttpResponse response = client.execute(get); //获得响应码。:响应码和服务器端发送给客户端的数据都封装在HttpResponse里。
int code = response.getStatusLine().getStatusCode(); if(code==200){ //成功响应。 //获得服务器端的数据。
HttpEntity entity = response.getEntity(); byte[] b = EntityUtils.toByteArray(entity); //将byte数组的数据写到文件中。
FileOutputStream fos = new FileOutputStream("f:\\a3.jpg"); fos.write(b); fos.close(); }