GET方法:代码请求部分直接附在路径的后面 因此没有输出流输出请求部分 并且容易泄密
String path="http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=";
String line=null;
try {
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream is=conn.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
while ((line=br.readLine())!=null) {
System.out.println(line);
}
POST方法:需要设置请求头 请求方法,保密性高,多使用
try {URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
String param="2015-1-1";
InputStream is=conn.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line=null;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
OutputStream out=conn.getOutputStream();
byte[] buffer=param.getBytes();
out.write(buffer);
out.flush();