程式來源:
Java URL处理
練習程式1:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://www.google.com/webhp?hl=zh-TW&ictx=2&sa=X&ved=0ahUKEwjq5562tNTkAhVsyosBHUcmBx0QPQgH");
System.out.println("URL:" + url.toString());
System.out.println("協議:" + url.getProtocol());
System.out.println("驗證信息:" + url.getAuthority());
System.out.println("文件名及請求參數:" + url.getFile());
System.out.println("主機名:" + url.getHost());
System.out.println("路徑:" + url.getPath());
System.out.println("端口:" + url.getPort());
System.out.println("默認端口:" + url.getDefaultPort());
System.out.println("請求參數:" + url.getQuery());
System.out.println("定位位置:" + url.getRef());
} catch (IOException e) {
e.printStackTrace();
}
}
}
URL:https://www.google.com/webhp?hl=zh-TW&ictx=2&sa=X&ved=0ahUKEwjq5562tNTkAhVsyosBHUcmBx0QPQgH
協議:https
驗證信息:www.google.com
文件名及請求參數:/webhp?hl=zh-TW&ictx=2&sa=X&ved=0ahUKEwjq5562tNTkAhVsyosBHUcmBx0QPQgH
主機名:www.google.com
路徑:/webhp
端口:-1
默認端口:443
請求參數:hl=zh-TW&ictx=2&sa=X&ved=0ahUKEwjq5562tNTkAhVsyosBHUcmBx0QPQgH
定位位置:null
練習程式2:用jsp把網頁全部複製過來
<%@ page import="java.io.*" %>
<%@ page import="java.net.HttpURLConnection" %>
<%@ page import="java.net.URL" %>
<%
URL obj = new URL("https://www.google.com");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
String urlString="";
while ((inputLine = in.readLine()) != null) {
urlString += inputLine;
}
in.close();
%>
<% out.println(urlString); %>
詳談java中File類getPath()、getAbsolutePath()、getCanonical的區別
Android - HttpURLConnection POST Json
HttpURLConnection java.io.FileNotFoundException
Convert array of strings into a string in Java
整理:
1
Receive JSON POST with PHP 要用:
$_POST = json_decode(file_get_contents('php://input'), true);
不能用
$_POST['param']
2 (Output 類似 寫 , 所以如果false,就不能 寫資料 到 server)
如果
connection.setDoOutput(false);
就不能
OutputStream out = connection.getOutputStream();
會有
java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
3
如果 (Input 類似 讀 , 所以如果false,就代表不能讀server回傳的資料)
connection.setDoInput(false);
就不能
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
會有
java.net.ProtocolException: Cannot read from URLConnection if doInput=false (call setDoInput(true))