2015年10月19日 星期一

Java 如何 取得http 網頁的 檔頭


Java 如何 取得http 網頁的 檔頭

How to get HTTP Response Header in Java
By mkyongmkyong | March 10, 2013 | Updated : January 8, 2014

This example shows you how to get the Http response header values in Java.

1. Standard JDK example.

URL obj = new URL("http://mkyong.com");
URLConnection conn = obj.openConnection();
//get all headers
Map> map = conn.getHeaderFields();
for (Map.Entry> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + 
                 " ,Value : " + entry.getValue());
}
//get header by 'key'
String server = conn.getHeaderField("Server");

2. Apache HttpClient example.

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://mkyong.com");
HttpResponse response = client.execute(request);
//get all headers
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
System.out.println("Key : " + header.getName() 
      + " ,Value : " + header.getValue());
}

//get header by 'key'
String server = response.getFirstHeader("Server").getValue();
1. URLConnection Example
See a full example to get response headers value via URLConnection.

ResponseHeaderUtil.java
package com.mkyong;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class ResponseHeaderUtil {

  public static void main(String[] args) {

    try {

URL obj = new URL("http://mkyong.com");
URLConnection conn = obj.openConnection();
Map> map = conn.getHeaderFields();

System.out.println("Printing Response Header...\n");

for (Map.Entry> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() 
                           + " ,Value : " + entry.getValue());
}

System.out.println("\nGet Response Header By Key ...\n");
String server = conn.getHeaderField("Server");

if (server == null) {
System.out.println("Key 'Server' is not found!");
} else {
System.out.println("Server - " + server);
}

System.out.println("\n Done");

    } catch (Exception e) {
e.printStackTrace();
    }

  }

}





其他
Not quite sure what you really want to do. But to see what is posted to the server you would have to post it to your own and read the data you receive there.
If you want to see all the REQUEST headers you could: 
for (String header : conn.getRequestProperties().keySet()) {
   if (header != null) {
     for (String value : conn.getRequestProperties().get(header)) {
        System.out.println(header + ":" + value);
      }
   }
}
Or after connecting you can print out the RESPONSE headers:
for (String header : conn.getHeaderFields().keySet()) {
   if (header != null) {
     for (String value : conn.getHeaderFields().get(header)) {
        System.out.println(header + ":" + value);
      }
   }
}

21個範例





    
/**
Copyright (C) 2004  Juho Vh-Herttua

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/


import java.io.*;
import java.util.*;
import java.text.*;
import java.net.URLDecoder;

public class HttpParser {
  private static final String[][] HttpReplies = {{"100", "Continue"},
                                                 {"101", "Switching Protocols"},
                                                 {"200", "OK"},
                                                 {"201", "Created"},
                                                 {"202", "Accepted"},
                                                 {"203", "Non-Authoritative Information"},
                                                 {"204", "No Content"},
                                                 {"205", "Reset Content"},
                                                 {"206", "Partial Content"},
                                                 {"300", "Multiple Choices"},
                                                 {"301", "Moved Permanently"},
                                                 {"302", "Found"},
                                                 {"303", "See Other"},
                                                 {"304", "Not Modified"},
                                                 {"305", "Use Proxy"},
                                                 {"306", "(Unused)"},
                                                 {"307", "Temporary Redirect"},
                                                 {"400", "Bad Request"},
                                                 {"401", "Unauthorized"},
                                                 {"402", "Payment Required"},
                                                 {"403", "Forbidden"},
                                                 {"404", "Not Found"},
                                                 {"405", "Method Not Allowed"},
                                                 {"406", "Not Acceptable"},
                                                 {"407", "Proxy Authentication Required"},
                                                 {"408", "Request Timeout"},
                                                 {"409", "Conflict"},
                                                 {"410", "Gone"},
                                                 {"411", "Length Required"},
                                                 {"412", "Precondition Failed"},
                                                 {"413", "Request Entity Too Large"},
                                                 {"414", "Request-URI Too Long"},
                                                 {"415", "Unsupported Media Type"},
                                                 {"416", "Requested Range Not Satisfiable"},
                                                 {"417", "Expectation Failed"},
                                                 {"500", "Internal Server Error"},
                                                 {"501", "Not Implemented"},
                                                 {"502", "Bad Gateway"},
                                                 {"503", "Service Unavailable"},
                                                 {"504", "Gateway Timeout"},
                                                 {"505", "HTTP Version Not Supported"}};

  private BufferedReader reader;
  private String method, url;
  private Hashtable headers, params;
  private int[] ver;

  public HttpParser(InputStream is) {
    reader = new BufferedReader(new InputStreamReader(is));
    method = "";
    url = "";
    headers = new Hashtable();
    params = new Hashtable();
    ver = new int[2];
  }

  public int parseRequest() throws IOException {
    String initial, prms[], cmd[], temp[];
    int ret, idx, i;

    ret = 200; // default is OK now
    initial = reader.readLine();
    if (initial == null || initial.length() == 0) return 0;
    if (Character.isWhitespace(initial.charAt(0))) {
      // starting whitespace, return bad request
      return 400;
    }

    cmd = initial.split("\\s");
    if (cmd.length != 3) {
      return 400;
    }

    if (cmd[2].indexOf("HTTP/") == 0 && cmd[2].indexOf('.') > 5) {
      temp = cmd[2].substring(5).split("\\.");
      try {
        ver[0] = Integer.parseInt(temp[0]);
        ver[1] = Integer.parseInt(temp[1]);
      } catch (NumberFormatException nfe) {
        ret = 400;
      }
    }
    else ret = 400;

    if (cmd[0].equals("GET") || cmd[0].equals("HEAD")) {
      method = cmd[0];

      idx = cmd[1].indexOf('?');
      if (idx < 0) url = cmd[1];
      else {
        url = URLDecoder.decode(cmd[1].substring(0, idx), "ISO-8859-1");
        prms = cmd[1].substring(idx+1).split("&");

        params = new Hashtable();
        for (i=0; i
          temp = prms[i].split("=");
          if (temp.length == 2) {
            // we use ISO-8859-1 as temporary charset and then
            // String.getBytes("ISO-8859-1") to get the data
            params.put(URLDecoder.decode(temp[0], "ISO-8859-1"),
                       URLDecoder.decode(temp[1], "ISO-8859-1"));
          }
          else if(temp.length == 1 && prms[i].indexOf('=') == prms[i].length()-1) {
            // handle empty string separatedly
            params.put(URLDecoder.decode(temp[0], "ISO-8859-1"), "");
          }
        }
      }
      parseHeaders();
      if (headers == null) ret = 400;
    }
    else if (cmd[0].equals("POST")) {
      ret = 501; // not implemented
    }
    else if (ver[0] == 1 && ver[1] >= 1) {
      if (cmd[0].equals("OPTIONS") ||
          cmd[0].equals("PUT") ||
          cmd[0].equals("DELETE") ||
          cmd[0].equals("TRACE") ||
          cmd[0].equals("CONNECT")) {
        ret = 501; // not implemented
      }
    }
    else {
      // meh not understand, bad request
      ret = 400;
    }

    if (ver[0] == 1 && ver[1] >= 1 && getHeader("Host") == null) {
      ret = 400;
    }

    return ret;
  }

  private void parseHeaders() throws IOException {
    String line;
    int idx;

    // that fscking rfc822 allows multiple lines, we don't care now
    line = reader.readLine();
    while (!line.equals("")) {
      idx = line.indexOf(':');
      if (idx < 0) {
        headers = null;
        break;
      }
      else {
        headers.put(line.substring(0, idx).toLowerCase(), line.substring(idx+1).trim());
      }
      line = reader.readLine();
    }
  }

  public String getMethod() {
    return method;
  }

  public String getHeader(String key) {
    if (headers != null)
      return (String) headers.get(key.toLowerCase());
    else return null;
  }

  public Hashtable getHeaders() {
    return headers;
  }

  public String getRequestURL() {
    return url;
  }

  public String getParam(String key) {
    return (String) params.get(key);
  }

  public Hashtable getParams() {
    return params;
  }

  public String getVersion() {
    return ver[0] + "." + ver[1];
  }

  public int compareVersion(int major, int minor) {
    if (major < ver[0]) return -1;
    else if (major > ver[0]) return 1;
    else if (minor < ver[1]) return -1;
    else if (minor > ver[1]) return 1;
    else return 0;
  }

  public static String getHttpReply(int codevalue) {
    String key, ret;
    int i;

    ret = null;
    key = "" + codevalue;
    for (i=0; i
      if (HttpReplies[i][0].equals(key)) {
        ret = codevalue + " " + HttpReplies[i][1];
        break;
      }
    }

    return ret;
  }

  public static String getDateHeader() {
    SimpleDateFormat format;
    String ret;

    format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    ret = "Date: " + format.format(new Date()) + " GMT";

    return ret;
  }
}

   

2015年10月18日 星期日

一個可以使用arduino 介面的ARM小板

https://www.pjrc.com/teensy/teensy31.html

一個可以使用arduino 介面的ARM小板

eensy 3.2 & 3.1 - New Features

Teensy 3.2

Teensy 3.2 has dedicated 3.3V regulator.穩壓
Teensy 3.1

Teensy 3.1 has gold plating for easier soldering.更新接點
Teensy 3.0

Teensy 3.0 has standard tin plating finish.標準版
Teensy 3.2 and 3.1 have the same size, shape & pinout; and are compatible with code written for Teensy 3.0. All are well supported on the Arduino IDE using Teensyduino.
Teensy 3.1 adds several new features, due to an upgraded microcontroller. Here are the highlights. A table of technical specifications is show below.

Teensy 3.2 adds a more powerful 3.3 volt regulator, with the ability to directly power ESP8266 Wifi, WIZ820io Ethernet and other power-hungry 3.3V add-on boards.加入穩壓電源與wifi網路

More Memory For Awesome Projects

The RAM has quadrupled since 3.0, from 16K to 64K. While 16K is plenty for nearly all Arduino libraries, 64K allows for more advanced applications. Icons and graphics for color displays and audio effects requiring delays, like reverb and chorus, will become possible on Teensy 3.2 & 3.1.
Flash memory has also doubled, to 256K, and provides double the memory bandwidth.

5 Volt Tolerance on Digital Inputs

Today most new chips use 3.3V signals, but many legacy products output 5 volt digital signals. These can now be directly connected to Teensy digital inputs.
All digital pins are 5 volt tolerant on Teensy 3.2 & 3.1. However, the analog-only pins (A10-A14), AREF, Program and Reset are 3.3V only.

Update: Color Change Jan 22, 2014


The color of Teensy 3.1 was changed from black to green on January 22, 2014.

板子使用的是ARM處理器
MK20DX128VLH5
Cortex-M4
48
96

就是個線上寫javascript 又可以直接測試的地方

http://jsfiddle.net

就是個線上寫javascript 又可以直接測試的地方

1. Run:執行你所輸入的 HTML, CSS, JavaScript 並顯示在右下角的 Result 視窗裡。

2. Update:儲存更新版本 ( 快速鍵為 Ctrl+S ),

3. Fork:把修改的內容更新到網頁去

4. Reset:將 HTML, CSS, JavaScript 這三個欄位的內容清空

5. TidyUp: HTML, CSS, JavaScript 這三個欄位的內容進行排版

6. JSLint:驗證 JavaScript 的語法是否符合。  


7. Discuss:線上討論

Sketchfab 算是一個 3d物件 的 空間 與 市集

https://sketchfab.com

Sketchfab is the leading platform to publish and find the best 3D content, anywhere online. Millions of people make 3D models or scan the real world in 3D, why would they share this in 2D? What YouTube did for video makers, or SoundCloud for musicians, we want to do for creators of 3D content.


You can upload files in almost any 3D format (we support 28), directly on sketchfab.com or using one of our exporters, in order to upload from your favorite 3D creation tool. Once your models are on Sketchfab, you can embed them on any web page, and share them on other platforms like Tumblr, WordPress, Bēhance, Facebook, Kickstarter, LinkedIn, deviantART…

Sketchfab 算是一個 3d物件 的 空間 與 市集

提供你出版3d物件 使用者必須 付費 換取大空間
Max upload size:
50MB for free accounts
200MB for PRO accounts
500MB for Business accounts
See plans & pricing

你可以用帳號建立如社群網站般 追蹤 分享 我的最愛 之類的
網站 可以 讓你像 youtube 一樣 只要簡單 一段分享 語法 就 嵌入一個瀏覽物件
你可以上傳多種 檔案格式 (28種)與 分享在 多種 平台 Tumblr, WordPress, Bēhance, Facebook, Kickstarter, LinkedIn, deviantART…

內容可以商業銷售物件或是提供下載

https://sketchfab.com/models/ea69a7088e1e481fb14723dcc31088d5




education Arduino 教育



http://littlebits.cc

  • 電子電路 兒童 教育 套件,所有教育板都透過重新設計,可以很方便的堆疊或串接,不用考慮電子電路設計的細節


http://www.jd-pioneer.com/littleBits/littleBits.htm

  • 繁體中文 的 科學教材 相關 設計介紹


http://orange.dataart.com/tag/arduino-yun/

  • 一篇有關 DeviceHive boards 多合一 實驗版 的介紹



http://www.rugged-circuits.com/ruggeduino

  • 設計者 將 原版 arduino 電路板 加上 電壓保護 或 介面電路


https://www.pretzellogix.net/2014/10/09/three-arduino-starter-kits-compared-and-reviewed/

  • 比較 多個 常見 實驗 元件 套組 的 介紹


http://www.seeedstudio.com/depot/8-SQUARE-Heartbeat-Necklace-Soldering-Kit-LED-MatrxAtmega328Arduino-Compatible-Microcontroller-p-1878.html

  • 中國大陸的購物網站


https://blog.arduino.cc/2013/05/20/two-kickstarter-projects-worth-look/

  • 溫濕度與小天氣盒和蜘蛛


https://www.kickstarter.com/projects/acrobotic/the-smart-citizen-kit-crowdsourced-environmental-m

  • 環境與天氣盒


 https://tltl.stanford.edu/projects/lightup

  • 將 電路元件 封裝成 積木 的 簡單 基本電路


http://www.sciencebuddies.org

  • 科學教育資訊


http://www.picocricket.com/picoboard.html

  • 一個 提供你 樂器 和 電壓量測 的 使用者 介面


https://en.wikipedia.org/wiki/Prototype

  • 維基百科 原形


https://www.matrixtsl.com/eblocks.php

  • 電子 電路 方塊 積木


http://www.snapcircuits.net/products/product_details/snap_circuits_pro_500_experiments=MzU4

  • 兒童 電子 電路 教育 玩具


http://blog.the-learning-tree.com/2008/10/15/electronics-are-a-snap-with-snap-circuits-jr/

  • 同上兒童 電子 電路 教育 玩具


https://learn.adafruit.com/firewalker-led-sneakers/overview

  • arduino 與 open source hardware 電路板 的 購物網




RobotLinking Uno Learning Kit with A Power Supply 9V-1A For Arduino With Tutorial

Build your own electronic circuits with the Electronics Learning Lab. It has over 200 projects that teach you about transistors, diodes, capacitors, oscillators, electronic circuits and schematic symbols. Plus, it has light-emitting diodes, an LED display and an analog panel meter that gives more visual options when building projects.


math.hws.edu vaughn askmanual Arduino Starter Kit manual HWS Department


Top 10 Science fair Electronics projects for School students

youtube "My Kids' First Breadboard Project"

This site supports my text Electronic Circuits for the Evil Genius, 2nd ed: McGraw-Hill.
The kit provides all components needed for the course, at a very reasonable cost.

RadioShack - electronics learning lab kit

Trossen Robotics Blog - Learn, Blog, Projects, Forums, Shipping, Customer Service, Contact

Ozobot Bit Makes Learning Block-Based Programming Fun

Industrial Training and the Best PLC Training for Maintenance
Updates on the “Arduino PLC”
Several people have contacted me regarding the “Teensy++ PLC”, either with the idea of extending it, or porting it to other microcontroller architectures, or developing it further as a true “Arduino” solution. Especially the true Arduino PLC solution is very tempting for me. Indeed, that was the idea that followed me from the very start. So, let me put together some thoughts on this topic.

This is the third part of our Circuits e-book series.

SAM: The Ultimate Internet Connected Electronics Kit







2015年10月17日 星期六

電機 電車 電動車 網站 自造者 Electric Vehicle EV Motor Controllers Motor Controller Assembly Directions website

Electric Vehicle EV Motor Controllers Motor Controller Assembly Directions

一個 電動車 自造者 的 資料 分享 網站

Paul & Sabrina’s EV Stuff!

Motor Controller Assembly Directions

Here is the link: P&S motor controller assembly directions Updated April 15, 2011



Welcome to PaulandSabrinasEVstuff.com Electric Motor Controllers

http://www.paulandsabrinasevstuff.com/index.html
http://www.paulandsabrinasevstuff.com/evmotorcontrollers.html


另一個

http://www.instructables.com/id/Homemade-100-HP-Motor-Controller-for-an-Electric-C/?ALLSTEPS




Homemade 100 HP Motor Controller for an Electric Car



This instructable explains how to build your own 100 HP (peak) motor controller for use in an electric car or 
motorcycle conversion.  It can take any voltage up to 144v, and the peak current is 500 amps.  The cost of
 the components is a few hundred dollars, which means you can save over $1000 by putting one together 
yourself.   At 144v, you can expect a top speed of around 75 MPH in a car. 
Check out  http://ecomodder.com/forum/open-revolt-open-sourhttp://ecomodder.com/forum/open-revolt-open-source-dc-motor-controller.htmlce-dc-motor-controller.html
if you want to read about the whole story!

Experience in soldering is important.  If you want to really keep costs down, a mill is helpful, but that work
 can be outsourced to a local metal shop.


You are going to need a control board and etched power board.  The power board needs to be at least 3 ounce copper.   Ebay is a good place to look for heavy cheap copper clad PCB.  For example:

You could print the picture from this link and somehow transfer it onto a piece of heavy blank PCB, and etch it with a dremel if you have a ver y steady hand.  The dimensions are 8"x6".  This link also has the G-code that you can use to etch with a CNC mill or you could give the G-code to a machine shop.

Picture 2 and 3 below is an example of an early power board I made with a Dremel.

You can get a control board from me or you can make the control board in your favorite PCB layout software using the schematic here::
http://home.cogeco.ca/~tkooistra/Cougar_Controller_Rev2C_Schematic.pdf
And here are some pictures of the PCB layers:

////////////////// 電機 測試 監控

    Projects

    I really enjoy working on projects. Much of what I do is software oriented, but I also enjoy electronics and other hands-on opportunities.
  • Software projects
  • Hardware projects
  • Other projects - such as hybrid hardware & software projects, or even completely non-technological projects

To-Do List

Here is a list of projects that I want to do, some are partially implemented as proof-of-concept, while others are mere ideas:
Repository management system. Needs to handle: git, hg, svn, cvs, fossil, etc... Provide simple mirroring and update features, etc...
Plant pot water level sensor. Raises an alarm when the plat needs watering - perhaps even one day turn on a tap too??
Pulse Oximeter. I've always liked the idea of developing medical equipment, this sounds easy, and I'd like to have one!
Smart PC Power Control/Monitor. I've got a basic power control and monitor setup for my PCs, but I'd like to develop this to a less prototype-esque state. Key features are remote power state monitor and control, and remote reset. The module acts like physical switches and runs on it's own... sort of like HP's iLO and Dell's DRAC, but as a retro-fit accessory.


////////////////// 直流馬達 無刷 三相 馬達



Atmels ATmega48 (or ATmega88 for smarter ones) that does all the work. For some weird reason Chinese manufacturers LOVE ATmega48, it is in every design. Like always it is clocked at 16MHz with resonator. AVR in this design is in QFN package, in most of the cases TQFP is more common.5V voltage regulator in D-pack and some ceramic capacitors.Maxim MAX662 12V 30mA charge pump for high side gate driving. The output of the charge pump is stored on the ceramic capacitor on the right.
International Rectifier IR2101S high and low side mosfet driver. One for every channel. On the right of every driver there is a diode and a capacitor. This is probably bootstrap circuit that collects higher voltage for gate driving from inductance spikes of outputs.
In between of gate drivers are resistors for feedback.
The top part is for BEC. It looks identical to very common switching regulator block used in ebay products. Texas Instruments LM2575, originally a 1A step-down but now apparently a 5A one.