搜尋此網誌

2013年10月8日 星期二

【Java】實作從html讀取JSON

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONfunctions {

        public static JSONObject getJSONfromURL(String url, int method) {
                InputStream is = null;
                String result = "";
                JSONObject jObject = null;

                // http post or get
                try {
                        HttpClient httpclient = new DefaultHttpClient();

                        if (method == Globals.METHOD_GET) {
                                HttpGet httpget = new HttpGet(url);
                                HttpResponse response = httpclient.execute(httpget);
                                HttpEntity entity = response.getEntity();
                                is = entity.getContent();
                        }
                        else if( method == Globals.METHOD_POST) {
                                HttpPost httppost = new HttpPost(url);
                                HttpResponse response = httpclient.execute(httppost);
                                HttpEntity entity = response.getEntity();
                                is = entity.getContent();
                        }
                        

                } catch (Exception e) {
                 System.out.printf("log_tag:Error in http connection " + e.toString());
                }

                // convert response to string
                try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        is, "utf-8"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                        is.close();
                        result = sb.toString();
                        System.out.printf("RESULT: %s", result);
                } catch (Exception e) {
                 System.out.printf("log_tag:Error converting result " + e.toString());
                }

                try {

                        jObject = new JSONObject(result);
                } catch (JSONException e) {
                 System.out.printf("log_tag:Error parsing data " + e.toString());
                }

                return jObject;
        }
}
class Globals {
 public final static int METHOD_GET = 1;
    public final static int METHOD_POST = 2;
}
參考:

  1. http://www.androidbegin.com/tutorial/android-parsing-yql-using-json-tutorial/ 
  2. https://code.google.com/p/cabbiemagnet/source/browse/trunk/CabbieMagnetAndroid/src/com/cabbiemagnet/android/?r=27

【JSON】簡介

JSON(Javascript Object Notation)

  • JSON結構
    • 物件型態(Object):
      • 以{}表示。
    • 陣列型態(Array)
      • 以[]表示。
  • JSON資料
    • "key":value:key和value之間用『:』隔開。
  • JSON value表示法
    • 數字(整數或浮點數)
    • 字串(需加上"",ex:"string")
    • 布林函數(boolean,true或者false)
    • NULL
  • 舉例:

{
  "orderID": 12345,
  "shopperName": "John Smith",
  "shopperEmail": "johnsmith@example.com",
  "contents": [
    {
      "productID": 34,
      "productName": "SuperWidget",
      "quantity": 1
    },
    {
      "productID": 56,
      "productName": "WonderWidget",
      "quantity": 3
    }
  ],
  "orderCompleted": true
}
參考:

  1. http://www.elated.com/articles/json-basics/

【JSON】JSON Pretty Print

http://jsonprettyprint.com/

【Java】JSON.jar教學

參考:
  1. http://www.ewdna.com/2008/10/jsonjar.html
  2. http://www.json.org/

轉載:

JSON in Java 並沒有提供 .jar下載,所以需要透過作者提供的source code打包下載,在包裝成.jar檔。
  1. 從 JSON in Java 連結到 github下載 Source Code
  2. 建立資料夾路徑 xxx/org/json/,其中 xxx 可以自訂,org/json/ 不可更改!
  3. 解壓縮 zip 檔裡的 JSONArray.java 等所有 java 檔至 xxx/org/json/ 底下,test資料夾不用。
  4. windows執行cmd,Linux執行terminal,切換至 xxx/。輸入指令 javac ./org/json/ *.java。
  5. 在 xxx/ 目錄下繼續輸入指令 jar -cvf json.jar ./org/json/*.class。
  6. 在目錄 xxx/ 底下看到 json.jar 就可以拿去 import 使用了。
此作者  已打包好的json.jar檔

不過我目前使用jre的版本是1.7版,在按照上述第4步驟,出現不少compile error,按照原作者的github說明jre應該是1.2 - 1.4版,所以不確定是否和jre版本有關係。

總之,先下載上述已打包的jar檔使用。

【Java】HTTP response code 505解決辦法

如題
URL url = new URL(urlstring.trim());                        
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();

解決辦法
需對url的parameter先作encode
String urlString = "http://test.com?param1=" + URLEncoder.encode(value1, "UTF-8") + "&param2=" + URLEncoder.encode(value2, "UTF-8") ;

URL url = new URL(urlstring.trim());                        
urlConnection = (HttpURLConnection) url.openConnection();
int response = urlConnection.getResponseCode();
參考:

  1. http://stackoverflow.com/questions/13252814/getting-505-responce-from-server
  2. http://stackoverflow.com/questions/3625659/java-io-ioexception-server-returns-http-response-code-505