Java 网络下载

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
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"));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值