通过Http协议获取网络资源,HttpURLConnection,HttpClient

使用java自带的包获取网络资源

public class TestHttpUrlConnection {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream boStream = null;
        try {
            // 1,创建URL对象 统一资源定位符 跟互联网的一个路径相关联
            URL url = new URL(
                    "http://www.xiufa.com/BJUI/plugins/kindeditor_4.1.10/attached/image/20160427/20160427020327_69298.png");
            // 2,创建HttpURLConnection对象 发起TCP连接
            HttpURLConnection hc = (HttpURLConnection) url.openConnection();
            // 3,设置请求参数
            hc.setDoInput(true);// 默认true,允许从互联网读入数据
            hc.setDoOutput(true);// 默认为false,允许向互联网写入数据
            hc.setRequestMethod("GET");// 默认为GET 单词一定要大写
            hc.setConnectTimeout(5000);// 设置连接超时时间
            hc.setReadTimeout(5000);// 设置读取数据的超时时间
            // 4,得到响应码 //404 找不到网页 500 服务端内部错误 400 :服务端没有开启服务等
            // 200 代表成功
            int code = hc.getResponseCode();

            if (code == 200) {
                // 5,得到对应的输入流
                bis = new BufferedInputStream(hc.getInputStream());
                System.out.println("文件总的大小:" + hc.getContentLength());
                boStream = new BufferedOutputStream(new FileOutputStream("girl.png"));
                byte b[] = new byte[1024 * 1024];// 缓冲区
                int len = 0;// 每次实际读取的字节数
                while ((len = bis.read(b)) != -1) {
                    boStream.write(b, 0, len);
                }
                System.out.println("下载完毕!");
            } else {
                System.out.println("请求失败");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (boStream != null) {
                try {
                    boStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

 1 import java.io.IOException;
 2 
 3 import org.apache.http.HttpEntity;
 4 import org.apache.http.HttpResponse;
 5 import org.apache.http.client.ClientProtocolException;
 6 import org.apache.http.client.HttpClient;
 7 import org.apache.http.client.methods.HttpGet;
 8 import org.apache.http.client.methods.HttpPost;
 9 import org.apache.http.impl.client.HttpClients;
10 import org.apache.http.util.EntityUtils;
11 
12 /**
13  * HttpClient需要org.apache.http的包
14  * 比java自带的包URL更方便获取网络资源
15  * Get和Post
16  * @author Administrator
17  *
18  */
19 public class TestHttpClient {
20     public static void main(String[] args) {
21         new Get().start();
22     }
23 }
24 class Get extends Thread{
25     @Override
26     public void run() {
27         HttpClient client=HttpClients.createDefault();//创造一个客服
28         HttpGet get=new HttpGet("http://www.baidu.com");//http地址
29         try {
30             HttpResponse response = client.execute(get);//客户执行http的请求得到回应
31             HttpEntity entity = response.getEntity();//获取 回应的实体
32             String result=EntityUtils.toString(entity, "utf-8");//通过实体的工具获取实体
33             System.out.println(result);//输出实体(就是读取的数据,通过浏览器就可以打开)
34         } catch (Exception e) {
35             e.printStackTrace();
36         } 
37     }
38 }
39 class Post extends Thread{
40     @Override
41     public void run() {
42         HttpClient client=HttpClients.createDefault();
43         HttpPost post=new HttpPost("https://www.baidu.com/s?tn=87048150_5_pg&cid=qb7.zhuye&ie=utf8&wd=%E5%9B%BE%E7%89%87&hdq=sogou-wsse-2f4ccb0f7a84f335");
44         try {
45             HttpResponse execute = client.execute(post);
46             HttpEntity entity = execute.getEntity();
47             String string = EntityUtils.toString(entity, "utf-8");
48             System.out.println(string);
49         } catch (Exception e) {
50             e.printStackTrace();
51         }
52     }
53 }

 HttpURLConnection使用的步骤:

GET 表示希望从服务器那里获取数据,而 POST 则
表示希望提交数据给服务器。写法如下:
connection.setRequestMethod("GET");
接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服
务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,示例写法如下:
connection.setConnectTimeout(8000);//当连接网络超过8秒就抛出异常
connection.setReadTimeout(8000);//从网络上读取数据超过8秒就抛出异常
之后再调用 getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是
对输入流进行读取

最后可以调用 disconnect()方法将这个 HTTP 连接关闭掉,如下所示:
connection.disconnect();

 

比如说我们想要向服务器提交用户名和密码,就可以这样写:

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

总结:

两种方式:

HttpURLConnection方式:

HttpClient方式:

 

HttpClient的例子:get方式:

public class Test {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            // 1,创建HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 2,创建请求对象 GET POST 注意指定地址
            HttpGet get = new HttpGet(
                    "http://dh2.kimg.cn/static/images/public/20160330/de12e1bb425286873d1237650c6312aa.jpg");
            // 3,执行请求 HttpClient+HttpXXX = HttpResponse
            HttpResponse response = httpClient.execute(get);
            // 4,得到响应码
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                // 5,得到响应的HttpEntity对象
                // HttpEntity是客户端服务端传递的载体
                HttpEntity entity = response.getEntity();
                bos = new BufferedOutputStream(new FileOutputStream("meinv1.jpg"));
                // 方法一
                // // 6,从HttpENtity中得到输入流InoutStream is= entity.getContent();
                // bis = new BufferedInputStream(entity.getContent());
                // byte b[] = new byte[1024 * 1024];
                // int len = 0;
                // while ((len = bis.read(b)) != -1) {
                // bos.write(b, 0, len);
                // bos.flush();
                // }
                
                // 方法二
                // 图片 音频
                byte b[] = EntityUtils.toByteArray(entity);
                bos.write(b);
                // 文本 json xml 普通的文本
                // String string = EntityUtils.toString(entity);

                System.out.println("ok");
            } else {
                System.out.println("请求失败");
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

 post方式:

public class TestPost {
    public static void main(String[] args) {
        BufferedReader bReader = null;
        try {
            // 1,创建HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();
            // 2,创建请求对象
            HttpPost httpPost = new HttpPost("http://172.20.136.5:8080/2016_05_27_server/login");
            // 注意Post请求需要进行如下操作
            // 集合类型为NameValuePair 或者NameValuePair的子类
            // NameValuePair 与 Hashtabl与类似 线程安全的 key value不能为null HashMap线程不安全的
            // 键值对
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            // 给list添加值
            // html <form><input ……> </form>
            list.add(new BasicNameValuePair("uname", "张三"));
            list.add(new BasicNameValuePair("pwd", "admin"));
            // 创建发送的HttpEntity对象(客户端给服务端发送的对象)
            HttpEntity requestEntity = new UrlEncodedFormEntity(list, "gbk");// 参数二
                                                                                // 处理中文乱码
            httpPost.setEntity(requestEntity);
            // 3,执行请求
            HttpResponse response = httpClient.execute(httpPost);
            // 4,得到响应码
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                // 5,得到响应的HttpEntity对象(服务端响应回来的)
                HttpEntity responseEntity = response.getEntity();
                // 方法一
                bReader = new BufferedReader(new InputStreamReader(responseEntity.getContent(), "gbk"));
                String line = null;
                while ((line = bReader.readLine()) != null) {
                    System.out.println(line);
                }

            }

        } 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();
        } finally {
            if (bReader != null) {
                try {
                    bReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

}

 通过HttpConnection发送POST请求:

 /**
     * POST请求获取数据
     */
    public static String postDownloadJson(String path){
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write("id=8203");//post的参数 xx=xx&yy=yy
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            }
            bos.close();
            return bos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

其实raw方式使用的是纯字符串的数据上传方式,所以在POST之前,可能需要手工的把一些json/text/xml格式的数据转换成字符串,是一种post原始请求,区别于form-data这种常用的key-value方式。

/**
     * post请求之raw请求
     */
    public static void httpTest() throws ClientProtocolException, IOException {
        String url = "http://114.55.31.79:7070/app/in/getTipsList.mou";
        String json = "{\"page\":\"1\"}";//参数
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");//请求头
        post.setHeader("X_version", "1");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        // Log.i("test",content);
        System.out.println(content);
    }

 

posted @ 2016-04-16 14:05  ts-android  阅读(595)  评论(0编辑  收藏  举报