HttpClient类:第三方 添加jar包 apache 提供
灵活:避免底层流的操作
步骤:
1 创建Client对象
HttpClient 接口 = new DefaultHttpClient();
2 创建请求方式对象
HttpGet(url) //url?a=1&b=2
HttpPost(url) //url
3 针对于post请求,多一步操作
NameValuePair par = new BasicNameValuePair(参数名,参数);
List<NameValuePair> list;
HttpEntity entity = new UrlEncodingFormEntity(list);
httpPost.setEntity(entity);
4 客户端对象执行请求方式,得到相应对象
HttpResponse = httpClient.execute(httpGet|httpPost);
5 获取状态码 200
httpResponse.getStatusLine().getStatusCode();
6 获取数据
HttpEntity httpEntity = httpResponse.getEntity(); 获得服务器响应的数据
1)通过流
InputStream is = httpEntity.getContent()
2)通过工具类
byte[] d = EntityUtils.toByteArray(httpEntity);
String str = EntityUtils.toString(httpEntity,"utf-8");
例:
1 import java.io.FileOutputStream; 2 import java.io.IOException; 3 import java.io.InputStream; 4 5 import org.apache.http.HttpEntity; 6 import org.apache.http.HttpResponse; 7 import org.apache.http.client.ClientProtocolException; 8 import org.apache.http.client.HttpClient; 9 import org.apache.http.client.methods.HttpGet; 10 import org.apache.http.impl.client.DefaultHttpClient; 11 import org.apache.http.util.EntityUtils; 12 13 //通过HttpClient,使用get请求获取网络图片 14 public class Client1 { 15 16 public static void main(String[] args) throws ClientProtocolException, IOException { 17 //1 创建客户端 18 HttpClient client = new DefaultHttpClient(); 19 //2 创建请求方式对象 20 String baseUrl = "http://10.0.171.234:8080/day28Server/a.jpg"; 21 HttpGet httpGet = new HttpGet(baseUrl); 22 //3 客户端执行请求方式,获取响应对象 23 HttpResponse httpResponse = client.execute(httpGet); 24 //4 判断状态码 200 成功 25 int code = httpResponse.getStatusLine().getStatusCode(); 26 if(code == 200){ 27 //5 获取服务器数据:服务器返回的数据就存在于该entity中 28 HttpEntity httpEntity = httpResponse.getEntity(); 29 //6 30 // 从数据载体中获得数据:方式一:使用IO流 31 // InputStream is = httpEntity.getContent(); 32 // FileOutputStream fos = new FileOutputStream("src/a.jpg"); 33 // int len =0; 34 // byte[] b = new byte[1024]; 35 // while((len=is.read(b))!=-1){ 36 // fos.write(b,0,len); 37 // fos.flush(); 38 // } 39 // fos.close(); 40 41 //从数据载体中获得数据:方式二 使用工具类 EntityUtils 从数据载体直接转换成字节数组 42 byte[] data = EntityUtils.toByteArray(httpEntity); 43 FileOutputStream fos = new FileOutputStream("src/b.jpg"); 44 fos.write(data); 45 fos.close(); 46 47 System.out.println("下载完毕"); 48 } 49 50 } 51 52 }