此程序可以建立HTTP通信,分别以GET和POST方式向WEB服务器提交信息,并接收WEB服务器返回的响应。
import java.io.*;
import java.net.*;
public class s311 {
public static void main(String[] args){
new ReadByGet().start();
}
}
class ReadByGet extends Thread{ //以GET方式获得服务器响应
@Override
public void run() {
try {
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is); //建立输入流
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder htmlList = new StringBuilder();
while((str=br.readLine())!=null){
htmlList.append(str);
}
//关闭资源
br.close();
isr.close();
is.close();
System.out.println(htmlList.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class ReadByPost extends Thread { //以POST方式获得服务器响应
@Override
public void run() {
try {
URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("encoding", "UTF-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("向服务器传递的参数");
bw.flush();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder htmlList = new StringBuilder();
while((str=br.readLine())!=null){
htmlList.append(str);
}
//关闭资源
System.out.println(htmlList.toString());
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果: