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

Java 网络下载

2015-08-22 11:50 435 查看
HttpURLConnection:
1.get方法:
// 需求:通过本程序,访问网络上(某台服务器)的一张图片,下载到本地,显示到手机界面上(copy文件夹)
// step1:获取图片资源的路径

String baseUrl = "https://www.baidu.com/img/bd_logo1.png";

InputStream inputStream = null;

FileOutputStream fos = null;

HttpURLConnection connection = null;

// step2:利用URL类

try {

URL url = new URL(baseUrl);// 将baseUrl所执行的路径,转为url类的对象

// step3:可以从url上打开连接

connection = (HttpURLConnection) url.openConnection();

// step4:设置参数

/**

* 此方法用于设置本次访问服务器的请求方式:

*

* 注意点1:默认为get请求

*

* 注意点2:所有的单词字母都大写

*/

connection.setRequestMethod("GET");// 设置请求方式,必须是大写*

connection.setConnectTimeout(5000);// 设置请求超时

// 打开流

/**

* 打开连接中的输入流:用户客户端读取服务器的数据

*

* 注意点:该方法的参数默认为true

*/

connection.setDoInput(true);// 打开连接中的输入流

/**

* 打开连接中的输出流:用于客户端将数据写给服务器的

*

* 注意点:该方法的参数默认为false

*/

connection.setDoOutput(true);// 打开连接中的输出流

connection.connect();// 连接操作,可以省略不写

// step5:应该判断状态码是否ok:

int code = connection.getResponseCode();

System.out.println("状态码:" + code);

if (code == HttpURLConnection.HTTP_OK) {

// ok表示的码为200,表示本次请求ok,可以获取数据了

// step6:要获取数据了

inputStream = connection.getInputStream();

String fileName = baseUrl

.substring(baseUrl.lastIndexOf("/") + 1);//从后往前找到第一个“\”的位置

File file = new File("c:\\copy", fileName);

fos = new FileOutputStream(file);

byte[] buf = new byte[1024];

int len = 0;

while ((len = inputStream.read(buf)) != -1) {

fos.write(buf, 0, len);

}

System.out.println("图片下载完毕。。");

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// step7:关闭

if (inputStream != null) {

try {

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (fos != null) {

try {

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (connection != null) {

connection.disconnect();

}

}
1.2 get带参
// 客户端模拟登录:get请求

// step1:提供服务器端的登录的路径

String baseUrl = "http://10.0.184.253:8080/Day28_Server/LoginServlet";

String params = "username=aaa&password=123";// 要传递的参数,固定格式:key1=value1&key1=value1

// 追加参数

// step2:创建url对象

/**

* 要访问的真正的路径:

*

* ?:区分符:?前是路径,?后是要传递的参数

*

* &:区分符:区分多个参数名值对

*

* =:名=值

*/

URL url = new URL(baseUrl + "?" + params);// 真正访问的路径:路径?要传递的参数

// step3:打开连接

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// step4:设置(可选)

connection.setRequestMethod("GET");

connection.setConnectTimeout(5000);

connection.setDoInput(true);// 用于读服务器给回信:响应

if (connection.getResponseCode() == 200) {

// 获取服务器端的响应

InputStream inputStream = connection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(

inputStream));

String result = br.readLine();

System.out.println("服务器回应:" + result);

2,post方法
// 模拟登录服务器:使用post请求

// 客户端:有数据传给服务器的:输出流,客户端:接收服务器返回的响应信息:输入流

// step1:获取服务器的地址:

String baseUrl = "http://10.0.184.253:8080/Day28_Server/LoginServlet";

// step2:创建url对象

URL url = new URL(baseUrl);

// step3:打开连接

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// step4:设置参数

connection.setConnectTimeout(5000);

connection.setRequestMethod("POST");// 不能省略的步骤:因为默认为get

connection.setDoInput(true);// 打开输入流:用于读服务器的响应信息,可以省略的方法:因为默认打开的

connection.setDoOutput(true);// 打开输出流:用于向服务器写数据:用户名和密码,不能省略的方法,因为默认为false

// 很重要的步骤:将参数(用户名和密码)写给服务器

// step5:将数据写给服务器

String params = "username=admin&password=123";

OutputStream outputStream = connection.getOutputStream();// 从连接中获取输出流,用于向服务器写数据

outputStream.write(params.getBytes());

System.out.println("客户端已经建数据写给服务器了。。。");

// step6:判断响应码,获取相应的结果

if (connection.getResponseCode() == 200) {

InputStream inputStream = connection.getInputStream();

byte[] buf = new byte[100];

int len = 0;

len = inputStream.read(buf);

System.out.println("服务器说:" + new String(buf, 0, len));

HttpClient: 导入apache包进行的网络访问

1,get
String baseUrl = "http://10.0.184.253:8080/Day28_Server/LoginServlet";
HttpClient httpClient = new DefaultHttpClient();

String params = "username=admin&password=1234";

HttpGet httpGet = new HttpGet(baseUrl + "?" + params);

HttpResponse httpResponse = httpClient.execute(httpGet);

if (httpResponse.getStatusLine().getStatusCode() == 200) {

HttpEntity httpEntity = httpResponse.getEntity();

System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
//byte[] buff=EntityUtils.toByteArray();

2,post
// post请求做登录

// step1:提供url路径

String baseUrl = "http://10.0.184.253:8080/Day28_Server/LoginServlet";

// step2:创建客户端对象

HttpClient httpClient = new DefaultHttpClient();

// step3:创建请求方式对象

HttpPost httpPost = new HttpPost(baseUrl);

// step4:将数据封装到HttpEntity中

String username = "admin";// 参数名:username:参数值:admin

String password = "123";

// 创建一个名值对对象:NameValuePair,将用户名以及对应的值,封装

NameValuePair pair1 = new BasicNameValuePair("username", username);

NameValuePair pair2 = new BasicNameValuePair("password", password);

// 将名值对,存入集合

List<NameValuePair> list = new ArrayList<>();

list.add(pair1);

list.add(pair2);

// 创建一个载体对象, 用于存储用户名和密码:

HttpEntity httpEntity1 = new UrlEncodedFormEntity(list);// 客户端给服务器的数据

// 将httpEntity1:(用户名和密码),挂在到httpPost上

httpPost.setEntity(httpEntity1);

HttpResponse httpResponse = httpClient.execute(httpPost);

StatusLine statusLine = httpResponse.getStatusLine();

System.out.println(statusLine);

System.out.println(statusLine.getProtocolVersion());

if (statusLine.getStatusCode() == 200) { //服务器响应码

HttpEntity httpEntity2 = httpResponse.getEntity();// 存储服务器给客户端的数据

System.out.println(EntityUtils.toString(httpEntity2, "utf-8"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: