Java HttpURLConnection 設定user-agent

摘要:Java HttpURLConnection 設定user-agent

        String respond = "";
        String gateway_url = "http://www.google.com.tw";
        HttpURLConnection conn = null;

        try
        {
            URL url = new URL(gateway_url);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-agent","Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
            conn.connect();

            BufferedReader reader = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
            String lines = "";

            while  ((lines  =  reader.readLine())  !=  null )
            {
                respond += lines;
            }

            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            //e.printStackTrace();
            respond = e.getMessage();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            conn =null;
        }