Get Post区别:
1.Get数据大小有限制,请求的参数内容直接显示在地址栏里面,相对不安全
2.Post数据没有大小限制,请求的参数内容,不会显示在地址栏里面,相对安全一些
一.Get方式请求
package httpurlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrator on 2016/7/30.
*/
public class Get {
private static final String path = "http://www.baidu.com";
public static void main(String[] args) {
httpurlconnetionGet(path);
}
public static void httpurlconnetionGet(String path){
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
//get方式请求
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
//发送请求
httpURLConnection.connect();
if (httpURLConnection.getResponseCode()== HttpURLConnection.HTTP_OK) {
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader((is)));
String len = null;
while ((len = br.readLine()) != null) {
System.out.println(len);
}
br.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二.Post方式
package httpurlconnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Administrator on 2016/7/30.
*/
public class Post {
private static final String path = "http://www.baidu.com";
public static void main(String[] args) {
httpurlconnectionPost(path);
}
public static void httpurlconnectionPost(String path){
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST"); //请求方式为POST
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setDoOutput(true); //设置向服务端写数据
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write("sjfsfjssljl"); //向服务端提交数据
bw.close();
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { //判断状态码是否为200
InputStream is = httpURLConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //读取从服务端返回的数据
String len = null;
while ((len = br.readLine()) != null) {
System.out.println(len);
}
br.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}