httpcomponents练习

来源:互联网 发布:2015年广告投放数据 编辑:程序博客网 时间:2024/05/17 02:41

package com.zhh.examples.client;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;public class SecondDemo {public static void main(String[] args) {String url = "http://www.zhh.com:8008/ptws/logaction.htm";HttpClient client = new DefaultHttpClient();try {//方式登录系统HttpPost post = new HttpPost(url);List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("username", "name"));nvps.add(new BasicNameValuePair("password", "1"));post.setEntity(new UrlEncodedFormEntity(nvps));HttpResponse response = client.execute(post);//遍历返回头 System.out.println("=================header==================");Header[] headers = response.getAllHeaders();for (Header h : headers) {System.out.println(h.getName() + " : " + h.getValue());}//显示返回内容System.out.println("=================content==================");HttpEntity entity = response.getEntity();System.out.println(response.getStatusLine());if (null != entity) {System.out.println("Response content length: "+ entity.getContentLength());System.out.println("Response content:\n"+ EntityUtils.toString(entity));}//尝试请求页面String url2 = "http://www.zhh.com:8008/ptws/showform.htm";HttpGet get = new HttpGet(url2);HttpResponse response2 = client.execute(get);HttpEntity entity2 = response2.getEntity();if (null != entity2) {System.out.println("=============================");System.out.println("Response content length: "+ entity2.getContentLength());System.out.println("Response content:\n"+ EntityUtils.toString(entity2));}//尝试调用excel导出的actionString url3 = "http://www.zhh.com:8008/ptws/excel_materials_out_list.htm";HttpGet get3 = new HttpGet(url3);HttpResponse response3 = client.execute(get3);String filePath = "c:/test.xls";File file = new File(filePath);            InputStream is = response3.getEntity().getContent();            OutputStream os = new FileOutputStream(file);                        int c;             while ((c = is.read()) != -1){            os.write(c);                os.flush();            }             is.close();            os.close();            } catch (Exception e) {} finally {client.getConnectionManager().shutdown();}}}

练习抓数据,直接上代码。初次使用,可能有误用的地方,仅当自己笔记。

访问的是自己电脑上跑在tomcat下的系统(www.zhh.com映射为127.0.0.1)。

原创粉丝点击