1. 程式人生 > >java呼叫http介面並解析返回的json物件

java呼叫http介面並解析返回的json物件

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

public class Test {

    //呼叫http介面
    @RequestMapping(value="testInterfaces.htm", method={RequestMethod.GET, RequestMethod.POST})
    public void testInterfaces(HttpServletRequest request) throws Exception{
        //傳入中文引數並設定編碼格式
        String param = "{\"url\":\"中文\"}";
        param = URLEncoder.encode(param, "UTF-8");
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
               URL realUrl = new URL("http://localhost/test.htm");
               // 開啟和URL之間的連線
               URLConnection conn = realUrl.openConnection();
               // 傳送POST請求必須設定如下兩行
               conn.setDoOutput(true);
               conn.setDoInput(true);
               // 獲取URLConnection物件對應的輸出流
               out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
               // 傳送請求引數
               out.print(param);          
               // flush輸出流的緩衝
               out.flush();
               // 定義BufferedReader輸入流來讀取URL的響應
               in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
               String line;
               while ((line = in.readLine()) != null) {
                   result += line;
               }
               //解析json物件
               JSONObject jsStr = JSONObject.fromObject(result);
               System.out.println(jsStr.get("firstName"));
            } catch (Exception e) {
               e.printStackTrace();
            }
    }

    //所呼叫的介面
    @RequestMapping(value = "test.htm", method = { RequestMethod.GET,RequestMethod.POST })
    @ResponseBody
    public JSONObject test(HttpServletRequest request)throws Exception {       
        JSONObject jsonObj = new JSONObject();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("firstName", "jack");
        jsonObj.putAll(map);
        return jsonObj;
    }

}