URL下载数据、模拟登录或上传

URL下载数据:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlDownLoad {
//从网上或服务器下载数据
public static void main(String[] args) {
         String path="http://img4.duitang.com/uploads/item/201306/20/20130620221932_FVnZK.thumb.600_0.jpeg";
     try {
     //将网址封装成url对象
URL url=new URL(path);
//建立连接,用url里面的openConnection方法打开连接。
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//设置一些属性
//1.请求方式,默认为GET必须为大写
connection.setRequestMethod("GET");
connection.setDoInput(true);//可读默认true
connection.setDoOutput(true);//可写,默认false
connection.setReadTimeout(5000);//请求超时时间
connection.connect();//连接
int code=connection.getResponseCode();//获得响应码:一般是200
//7判断是否为200,表示成功
if(code==200){
//读取服务器发送过来的数据,获得读取管道
InputStream is=connection.getInputStream();
//存放地址
OutputStream os=new FileOutputStream("e:\\600_0.jpeg");
byte []a=new byte[1024];//缓冲数组
int len=-1;
while((len=is.read(a))!=-1){
os.write(a, 0, len);
}
is.close();
os.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
模拟登录:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUpLoad {
    //url模拟登录,可以变一下变成上传数据
public static void main(String[] args) {
String path = "http://localhost:8080/MyServer/login";
      try {
URL url=new URL(path);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//上传请求方式为Post,大写
connection.setRequestMethod("POST");
//要设置可写,因为默认为false
connection.setDoOutput(true);
//将数据写到流中。
//先获得写入流。
OutputStream os=connection.getOutputStream();
os.write("username=admin&userpwd=111".getBytes());
connection.connect();
int code=connection.getResponseCode();//响应码200
if(code==HttpURLConnection.HTTP_OK){//代表200
//打印服务器那边返回的信息
          InputStream is=connection.getInputStream();
              byte[]a=new byte[1024];
              int len=is.read(a);
              System.out.println(new String(a,0,len));
              is.close();
}
        os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

转载于:https://my.oschina.net/u/2541146/blog/596480

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值