1. 程式人生 > >Java以GET和POST方式實現HTTP通訊

Java以GET和POST方式實現HTTP通訊

 此程式可以建立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(); } } }

結果:
在這裡插入圖片描述