HttpClient下载图片和向服务器提交数据实例

使用 HttpClient 需要以下 6 个步骤:
1. 创建 HttpClient 的实例
2. 创建某种连接方法的实例,在这里是GetMethod。在 GetMethod 的 构造函数中传入待连接的地址
3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
4. 读 response
5. 释放连接。无论执行方法是否成功,都必须释放连接
6. 对得到后的内容进行处理
public class DemoHttpClient03 {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		
		//1,导包
		//2,得到HttpClient对象
			HttpClient client = new DefaultHttpClient();
			
		//3,设置请求方式
			HttpGet get = new HttpGet("http://photocdn.sohu.com/20150610/mp18368185_1433925691994_5.jpg");
		
		//4,执行请求, 获取响应信息
			HttpResponse response = client.execute(get);
			
			if(response.getStatusLine().getStatusCode() == 200)
			{
				//得到实体
				HttpEntity entity = response.getEntity();
				
				byte[] data = EntityUtils.toByteArray(entity);
				
				//图片存入磁盘
				FileOutputStream fos = new FileOutputStream("d:/mpl.jpg");
				fos.write(data);
				fos.close();
				
				System.out.println("图片下载成功!!!!");	
			}
	}
}

public class DemoHttpClient04 {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		//1, 导包
		//2, 得到HttpClient对象
			HttpClient client = new DefaultHttpClient();
		//3, 设置请求方式 post
			HttpPost post = new HttpPost("http://localhost:8080/Day_28_Servlet/LoginServlet");
		//6, List<BasicNameValuePair>
			List<BasicNameValuePair> parameters = new ArrayList();
			BasicNameValuePair p1 = new BasicNameValuePair("useName", "abc");
			parameters.add(p1);
			
			BasicNameValuePair p2 = new BasicNameValuePair("usePwd", "123");
			parameters.add(p2);
			
		//5, 请求"实体" (封装请求参数的对象)
			HttpEntity entity = new UrlEncodedFormEntity(parameters);
		//4, 需要给post中加入参数
			post.setEntity(entity);

		//7, 执行请求, 获取响应
		    HttpResponse response = client.execute(post);
		
		    if(response.getStatusLine().getStatusCode() ==200)
		    {
		    	//得到响应的实体
		    	HttpEntity responseEntity  = response.getEntity();
		    	
		    	String str = EntityUtils.toString(responseEntity);
		    	
		    	System.out.println("响应的内容为 : " + str);
            }
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值