HttpURLConnection分为两个部分,分为两个部分,请求和回复,回复的时候根据回复的内容来读取。
通过URL.openConnection来得到HttpURLConnection的对象。请求部分分为GET请求和POST 请求,POST请求更安全.都是需要设置请求时间等。
POST 请求还需要设置请求的数据,例如HashMap 来设置键值对,然后通过遍历得到具体的要提交的数据。值的部分 需要通过URLEncode来编码,
POST 请求还需要设置请求的属性,有两个属性必须要设置,Content-Type和Content-Length
POST 请求还需要通过OutputStream 来将数据提交给服务器端。
收到信息回复的时候,如果返回码为200说明正确了,这个时候我们要根据需求来决定使用哪一种输出流,如果需要保存在本地那么就使用FileOutputStream,
如果是仅仅是一次性的信息,可以使用ByteArrayOutputStream来在内存读取,然后释放就好了。
0:HttpURLConnection GET 请求,HttpURLConnection POST 请求
0.1GET 请求:
URL url = new URL("http://192.168.1.106:8080/tomcat.png");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setDoInput(true);
0.2 POST 请求:
url = new URL("http://192.168.1.106:8080/ServerDemo/servlet/LoginServlert");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(5000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);//设置可以向服务器传递数据
上面的都几乎一样,最关键的就是这里设置属性的部分,需要设置两个属性,一个是内容类型,一个是内容的长度。然后输出。
通过这里的输出,其实我们也可以是图片或者文件,这样就实现了文件的上传的功能。
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置提交的内容的类
byte[] data = sb.toString().getBytes("utf-8");//注意这里的编码utf-8
urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));//设置提交的内容的长度
//提交数据
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(data);
outputStream.close();
请求的数据,方法一:
StringBuilder sb = new StringBuilder("username=哈哈&password=psw");
请求的数据,方法二:
HashMap<String,String> params = new HashMap<String,String>();
params.put("username", "哈哈");
params.put("password", "psw");
StringBuilder sb = new StringBuilder();//把要提交的 数据类型定义为 username=哈哈&password=psw的格式
for(Map.Entry<String,String> en:params.entrySet()){//通过Map的遍历的到
sb.append(en.getKey())
.append("=")
.append(URLEncoder.encode(en.getValue(), "utf-8"))//这里的编码别忘记了。
.append("&");
}
sb.deleteCharAt(sb.length()-1);//删除最后一个&,注意 这里是 length-1,因为是从0开始计数的。
1:接收回复信息
返回信息的读取:读取的时候因为有的数据对于我们是没有必要存储的,有的是需要存储的。需要存储的我们使用FileOutputStream 将它写入到文件中,不需要存储的我们通过Byte