以下都是實(shí)戰(zhàn)經(jīng)驗(yàn):
1、Socket讀取
String strServer=
http://www.google.cn;//這里同樣可以用ip來(lái)訪問(wèn):203.208.35.100
String strPage="/language_tools?hl=zh-CN";
try {
String hostname = strServer;
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
wr.write("GET " + strPage + " HTTP/1.0\r\n");
wr.write("HOST:" + strServer + "\r\n");
wr.write("\r\n");
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
System.out.println(e.toString());
}
2、HttpClient方式
HttpClient client=new HttpClient();
GetMethod method=new GetMethod("
int status=client.executeMethod(method);
if(status==HttpStatus.SC_OK){
//讀取內(nèi)容
byte[] responseBody = method.getResponseBody();
//處理內(nèi)容
System.out.println(new String(responseBody));
System.out.println("文件名稱:"+method.getPath());
}
3、HttpURLConnection方式
URL url = new URL("這里是你要連接的地址");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);//是否可用于輸出(輸出參數(shù)),默認(rèn)為fasle。另:setDoInput()為是否可用于輸入,默認(rèn)為true
String parameters = "name=admin&password=123456";//這里是要傳遞的參數(shù)
OutputStream os = conn.getOutputStream();
os.write(parameters.getBytes("utf-8"));
os.flush();
os.close();
System.out.println("返回狀態(tài)碼:"+conn.getResponseCode());
System.out.println("返回消息:"+conn.getResponseMessage());
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
String line = null;
while((line=br.readLine())!=null){
System.out.println(line);
}
// DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
// DocumentBuilder db = dbf.newDocumentBuilder();
// Document doc = db.parse(is);
如果誰(shuí)還有更多的方式分享,請(qǐng)留言!