1. 程式人生 > >Java程式碼:呼叫外部介面(使用Json格式傳遞引數)的方法

Java程式碼:呼叫外部介面(使用Json格式傳遞引數)的方法

程式碼如下:

        String url="所給外部介面的url";
        //建立連線物件
        HttpClient httpClient = new HttpClient();
        //建立請求
        PostMethod method = new PostMethod(url);
        //設定請求頭格式為json格式
        RequestEntity entity=new StringRequestEntity(json,"application/json","UTF-8");
        //設定請求體資訊
        method.setRequestEntity(entity);
        //設定請求頭資訊
method.setRequestHeader("APPKEY", "C6C6E17AC153ED8DF8D61207"); //建立連線 httpClient.executeMethod(method); //獲取返回資訊 InputStream in = method.getResponseBodyAsStream(); InputStreamReader isr = new InputStreamReader(in, "UTF-8"); char[] b = new char
[4096]; for(int n; (n = isr.read(b)) != -1;) { sb.append(new String(b, 0, n)); } String returnStr = sb.toString();