您的位置:首页 > 理论基础 > 计算机网络

Java基础 笔记(八)-http

2015-08-26 09:32 465 查看
URL方式:使用get方式获取服务器端的一张图片

String path = "http://localhost:8080/Web/mokey.png";
        FileOutputStream fos = null;
        InputStream in = null;
        URL url = new URL(path);
        URLConnection conn = url.openConnection();
        HttpURLConnection con = (HttpURLConnection) conn;
        // 设置请求方式
        con.setRequestMethod("GET");
        // 设置连接的超时时间
        con.setConnectTimeout(5000);
        // 设置可以从服务器端读取数据
        con.setDoInput(true);

        // 获取服务器端的响应码
        if (con.getResponseCode() == 200) {
            // 读取服务器端返回的请求资源的数据
            in = con.getInputStream();
            fos = new FileOutputStream("file\\s1.png");
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len = in.read(arr)) != -1) {
                fos.write(arr, 0, len);
            }
        }
//关闭资源
        in.close();
       fos.close();


URL方式:使用post方式向服务器端提交数据并获取服务器端返回的数据

String path = "http://localhost:8080/web/servlet/LoginServlet";
        //定义要提交到服务器端的数据
        HashMap<String,String> data = new HashMap<String,String>();
        data.put("username", "呵呵");
        data.put("pwd", "1234");

        //把要提交的数据组织成username=weqe&pwd=123格式
        StringBuilder sb = new StringBuilder();
        for(Map.Entry<String,String> en:data.entrySet())
        {
            sb.append(en.getKey()).append("=")
              .append(URLEncoder.encode(en.getValue(),"utf-8")).append("&");
        }
        //去掉最后的&
        sb.deleteCharAt(sb.length()-1);

        //连接服务器并发送头信息
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);
        //设置可以向服务器端发送数据
        conn.setDoOutput(true);     
        //设置请求的头信息
        //设置提交的数据的类型
        conn.setRequestProperty("Content-Type"," application/x-www-form-urlencoded");       
        //设置提交的数据的长度
        byte[] b = sb.toString().getBytes("utf-8");     conn.setRequestProperty("Content-Length",String.valueOf(b.length));     
        //发送用户名和密码
        OutputStream out = conn.getOutputStream();
        out.write(b,0,b.length);
        out.close();

        //获取响应的信息
        if(conn.getResponseCode()==200)
        {
            InputStream in = conn.getInputStream();
            byte[] arr  = new byte[1024];
            int len =in.read(arr);
            System.out.println(new   String(arr,0,len,"utf-8"));            
}


通过Apache开源工具包:

public static String sendByPost(HashMap<String,String> map,String path,String encode) throws ClientProtocolException, IOException
    {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for(Map.Entry<String,String> en:map.entrySet())
        {
            list.add(new BasicNameValuePair(en.getKey(),en.getValue()));
        }
        //把要提交的表单数组织成username=weqe&psw=123格式
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode);        
        HttpPost post = new HttpPost(path);//提交方式对象
        post.setEntity(entity);     
        HttpClient client = new DefaultHttpClient();//执行提交的对
        //执行提交
        HttpResponse response = client.execute(post);       
        if(response.getStatusLine().getStatusCode()==200)
        {
            //获取读取流
            InputStream in = response.getEntity().getContent();
            return checkLogin(in,encode);
        }
        return null;
    }
    private static String checkLogin(InputStream in, String encode) throws IOException {
//把从服务器得到的数据暂存在内存流中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] arr = new byte[1024];
        int len =0;
        while((len = in.read(arr))!=-1)
        {
            bos.write(arr,0,len);
        }
        byte[] b= bos.toByteArray();
        String ss = new String(b,0,b.length,encode);
        return ss;
}


调用:
String path = "http://localhost:8080/web/servlet/LoginServlet";
HashMap<String,String> map = new HashMap<String,String>();
map.put("username", "呵呵");
map.put("pwd", "123");
String result = HttpUtil.sendByPost(map, path, "utf-8");
System.out.println(result);


引用:

jvm垃圾收集器与内存分配

强引用—>

指在程序中普遍存在,类似Object obj = new Object();这类的引用,只要强引用还存在,垃圾收集器永远不会回收被引用的对象。

软引用–>

给”hello”创键了一个软引用,这时有一个强引用str,还有一个软引用指向”hello”

泛型是引用所指向的对象的类型

当内存不足时,具备软引用的对象会被回收

String str = “hello”;

SoftReference soft = new SoftReference(str);

弱引用–>

给”hello”创键了一个弱引用,这时有一个强引用str,还有一个弱引用指向”hello”

只要被垃圾回收线程发现,就会被回收,不管内存足不足

WeakReference weak = new WeakReference(str);

虚引用–>

//给”hello”创键了一个 虚引用,这时有一个强引用str,还有一个虚引用指向”hello”

//虚引用实际并没有指向这个对象,创建虚引用只是为了提高对象被回收的机率,

//因为它并没有指向这个对象,所以必须结合着队列,当虚引用指向的对象被回收了,虚引用会被放入队列

ReferenceQueue queue = new ReferenceQueue<>();

PhantomReference phantom = new PhantomReference(str, queue);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: