url应用

package com.url;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 TestHttpClient2 {

public static void main(String[] args) {
    //http://localhost:8080/web1509/LoginServlet
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/web1509/LoginServlet");
    //设置提交的数据实体
    List<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("uname", "king"));
    list.add(new BasicNameValuePair("pwd", "20"));
    try {
        post.setEntity(new UrlEncodedFormEntity(list, "gbk"));
        //发送请求
        HttpResponse res = client.execute(post);
        //状态码
        int code = res.getStatusLine().getStatusCode();
        if(code==200){
            HttpEntity en= res.getEntity();
            String str = EntityUtils.toString(en, "gbk");
            System.out.println(str);
        }
        client.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static void test1() {
    //1.创建一个浏览器对象
    HttpClient client = new DefaultHttpClient();
    //2.创建请求方式的对象是
    HttpGet get = new HttpGet("http://localhost:8080/web1509/dog.jpg");


    try {
        //3.发送请求
    HttpResponse res=client.execute(get);
        //4.获得状态码
        int code = res.getStatusLine().getStatusCode();
        if(code==200){
            InputStream is =res.getEntity().getContent();
            int len =0;
            FileOutputStream fos = new FileOutputStream("d:\\cc.jpg");
            while((len=is.read())!=-1){
                fos.write(len);
                fos.flush();
            }
            fos.close();
            is.close();
            client.getConnectionManager().shutdown(); //关闭连接
            System.out.println("下载成功");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
package com.url;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
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.ClientProtocolException;
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.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class TestHttpClient {

public static void main(String[] args) throws ClientProtocolException, IOException {
    //1.打开浏览器
    HttpClient client = new DefaultHttpClient();
    //2.输入地址
    HttpPost post = new HttpPost("http://localhost:8080/web1509/LoginServlet");
    //如果是POST请求,必须指定提交的数据实体
    List<NameValuePair> list = new ArrayList<>();
    list.add(new BasicNameValuePair("uname", "king"));
    list.add(new BasicNameValuePair("pwd", "20"));
    post.setEntity(new UrlEncodedFormEntity(list, "gbk"));
    //3.回车
    HttpResponse res=client.execute(post);
    //得到响应状态码
    int code = res.getStatusLine().getStatusCode();
    if(code==200){
        InputStream is = res.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();
        System.out.println(line);
        br.close();

    }
}

private static void test1() {
    //http://localhost:8080/web1509/LoginServlet?uname="+name+"&pwd="+pwd
    //1.打开浏览器
    HttpClient client = new DefaultHttpClient();
    //2.输入地址
    String name ="king";
    String pwd="20";
    HttpGet hg = new HttpGet("http://localhost:8080/web1509/LoginServlet?uname="+name+"&pwd="+pwd);
    //3.敲回车
    try {
    HttpResponse response=client.execute(hg);
    int code = response.getStatusLine().getStatusCode(); //得到状态码
    if(code==200){
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine();
        System.out.println(line);
        br.close();

    }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

package com.url;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TestUrlHttpConnection {

public static void main(String[] args) {
    //一边下载,一边听
    //要用两个线程,主线程下载,子线程听
    try {
        final URL url = new URL("http://localhost:8080/web1509/dog.jpg");
        new Thread(new Runnable() {

            @Override
            public void run() {
                //进行下载保存到本地的
                DownLoadUtil.saveImage(url, new ShowOk() {

                    @Override
                    public void showRs(byte[] b) {
                        String str = new String(b);
                        System.out.println(str);

                    }
                });
            }
        }).start();

        DownLoadUtil.showImage(url, new ShowOk() {

            @Override
            public void showRs(byte[] b) {
                for (int i = 0; i <b.length; i++) {
                    System.out.println(b[i]);
                }

            }
        });
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

}

}

class DownLoadUtil{
public static void saveImage(URL url,ShowOk ok){
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“POST”);
int state = conn.getResponseCode();
if(state==200){
InputStream is = conn.getInputStream();
int len = 0;
FileOutputStream fos = new FileOutputStream(new File(“d:\ss.jpg”));
while((len=is.read())!=-1){
fos.write(len);
fos.flush();
}
fos.close();
is.close();
conn.disconnect();
ok.showRs(“下载到本地成功”.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static void showImage(URL url,ShowOk ok){
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        int state = conn.getResponseCode();
        if(state==200){
            InputStream is = conn.getInputStream();
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while((len=is.read())!=-1){
                bos.write(len);
            }
            bos.close();
            is.close();
            conn.disconnect();
            ok.showRs(bos.toByteArray());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

//用于提示的接口
interface ShowOk{
void showRs(byte[] b);
}

package com.url;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class URLHttpConnectionDemo {

public static void main(String[] args) {


    Scanner in = new Scanner(System.in);
    System.out.println("请输入用户名:");
    String name = in.next();
    System.out.println("请输入密码:");
    String pwd = in.next();

    try {
        //1.创建一个URL对象
        URL url = new URL("http://localhost:8080/web1509/LoginServlet?uname="+name+"&pwd="+pwd);
        //2.建立程序与资源之间的连接并打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3.设置请求的方式
        conn.setRequestMethod("GET");
        //4.必须设置操作流的方式,如果要是GET请求,就无需设置
        conn.setDoOutput(true);

        //6.获是响应状态码
        int state = conn.getResponseCode();
        //7.判断状态码
        if(state==200){
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            System.out.println("服务器端的响应:"+line);
            br.close();
        }

        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private static void test2() {
    Scanner in = new Scanner(System.in);
    System.out.println("请输入用户名:");
    String name = in.next();
    System.out.println("请输入密码:");
    String pwd = in.next();

    try {
        //1.创建一个URL对象
        URL url = new URL("http://localhost:8080/web1509/LoginServlet");
        String param = "uname="+name+"&pwd="+pwd;
        //2.建立程序与资源之间的连接并打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3.设置请求的方式
        conn.setRequestMethod("POST");
        //4.必须设置操作流的方式,如果要是GET请求,就无需设置
        conn.setDoOutput(true);
        //5.往服务器写内容,一定要放在获得状态码前
        OutputStream os = conn.getOutputStream(); //获得输出流
        os.write(param.getBytes()); //往服务器写
        os.flush();
        //6.获是响应状态码
        int state = conn.getResponseCode();
        //7.判断状态码
        if(state==200){
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            System.out.println("服务器端的响应:"+line);
            br.close();
        }
        os.close();

        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private static void test1() {
    try {
        //从指定的服务器上下载图片
        String address = "http://localhost:8080/web1509/dog.jpg";
        //1.通过地址构建一个URL对象
        URL url = new URL(address);
        //2.建立程序与资源之间的连接
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        //3.设置请求的方式
        conn.setRequestMethod("GET");
        //4.设置可以读取服务的内容,默认就是可以读取的
        conn.setDoInput(true); //默认就是true
        //5.获得一下服务器响应的状态,看有没有连接成功
        int state = conn.getResponseCode();
        FileOutputStream fos = null;
        //6.判断状态码的值,如果是200,表示连接成功,可以进行下载
        if(state==conn.HTTP_OK){
            //7.获得输入流
            InputStream is = conn.getInputStream();
            int len = 0;
            fos = new FileOutputStream(new File("d:\\dog.jpg"));
            while((len=is.read())!=-1){
                fos.write(len);
                fos.flush();
            }

            //8.释放资源
            fos.close();
            is.close();
            conn.disconnect(); //断开连接
            System.out.println("下载成功");
        }



    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值