java中GET方式提交的示例:
/*** 獲取關注列表;* @return*/@SuppressWarnings("unchecked")public static ArrayList<String> getUserList() {StringBuffer bufferRes = new StringBuffer();ArrayList<String> users = null;try {URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + TokenProxys.accessTokens());//URL realUrl = new URL("https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=" + TokenProxys.accessTokens()); HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();// 請求方式 conn.setDoOutput(true);conn.setDoInput(true);conn.setRequestMethod("GET");conn.setUseCaches(false);conn.setInstanceFollowRedirects(true);conn.setRequestProperty("Content-Type","application/json");conn.connect();// 獲取URLConnection對象對應的輸入流 InputStream in =conn.getInputStream();BufferedReader read =new BufferedReader(new InputStreamReader(in,"UTF-8"));String valueString =null;while ((valueString=read.readLine())!=null){bufferRes.append(valueString);}System.out.println(bufferRes);in.close();if (conn !=null){// 關閉連接 conn.disconnect();}} catch (Exception e) {e.printStackTrace();}//將返回的字符串轉換成json JSONObject jsonObject = JSONObject.fromObject(bufferRes.toString());//解析json中表示openid的列表 JSONObject data = (JSONObject)jsonObject.get("data");if(data!=null){//將openid列表轉化成數組保存 users = new ArrayList<String>(data.getJSONArray("openid"));//獲取關注者總數int count = Integer.parseInt(jsonObject.get("total").toString());if(count>1000){JSONObject object = jsonObject;String next_openid = null;JSONObject ob_data = null;ArrayList<String> ob_user = null;//大于1000需要多次獲取,或許次數為count/1000for(int i=0;i<count/1000;i++){//解析出下次獲取的啟示openid next_openid = object.get("next_openid").toString();object = getUserJson(next_openid);ob_data = (JSONObject)object.get("data");ob_user = new ArrayList<String>(ob_data.getJSONArray("openid"));for(String open_id : ob_user){//將多次獲取的openid添加到同一個數組 users.add(open_id);}}}}return users;}
java中POST方式提交的示例:
public static void main(String[] args) {try { String pathUrl = "https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token=zN6OKXWAdBKdwPUc1CFXIW-czck3W1CURoKr38Xy7jjDpyIxrpmSyfglAY1Bnvq3FePZbFVUzpeLfWC9lml7ENeApBJhSDXE-BRrHCmBsTk4gUI6DxxDgrGekrdkUSDkETAhAGAZOV"; // 建立連接 URL url = new URL(pathUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); // //設置連接屬性 httpConn.setDoOutput(true);// 使用 URL 連接進行輸出 httpConn.setDoInput(true);// 使用 URL 連接進行輸入 httpConn.setUseCaches(false);// 忽略緩存 httpConn.setRequestMethod("POST");// 設置URL請求方法//POST請求設置所需要的JSON數據格式{"tagid" : 134,"next_openid":""//第一個拉取的OPENID,不填默認從頭開始拉取}List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();Map<String, Object> map = new HashMap<String, Object>();map.put("tagid", 104);map.put("next_openid","");list.add(map);JSONArray arry=JSONArray.fromObject(map);String requestString = arry.toString().replace("[", "").replace("]", "");// 設置請求屬性 // 獲得數據字節數據,請求數據流的編碼,必須和下面服務器端處理請求流的編碼一致 byte[] requestStringBytes = requestString.getBytes("utf-8"); httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length); httpConn.setRequestProperty("Content-Type", "application/octet-stream"); httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長連接 httpConn.setRequestProperty("Charset", "UTF-8"); // 建立輸出流,并寫入數據 OutputStream outputStream = httpConn.getOutputStream(); outputStream.write(requestStringBytes); outputStream.close(); // 獲得響應狀態 int responseCode = httpConn.getResponseCode(); if (HttpURLConnection.HTTP_OK == responseCode) {// 連接成功 // 當正確響應時處理數據 StringBuffer sb = new StringBuffer(); String readLine; BufferedReader responseReader; // 處理響應流,必須與服務器響應流輸出的編碼一致 responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } responseReader.close(); System.err.println(sb.toString());} } catch (Exception ex) { ex.printStackTrace(); } }
?post請求向服務器傳遞參數的另外一種形式:
服務器端接受參數:String datas= request.getParameter("datas");
public static void sendPost() throws IOException{List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();Map<String, Object> map = new HashMap<String, Object>();map.put("phone", "phone");list.add(map);JSONArray arry=JSONArray.fromObject(map);String requestString = arry.toString();String result="";PrintWriter out = null; BufferedReader in = null; String pathUrl = "http://shuilangyizu.iask.in/app/appWechatDataController/wchatInfo.do";URL url=null;try {url = new URL(pathUrl);URLConnection connect = url.openConnection();connect.setRequestProperty("content-type","application/x-www-form-urlencoded;charset=utf-8");connect.setRequestProperty("method","POST");byte[] bytes= requestString.getBytes("utf-8") ;connect.setDoOutput(true); connect.setDoInput(true); out = new PrintWriter(connect.getOutputStream()); // 發送請求參數 out.print("datas="+requestString);out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connect.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } System.out.println(result); } catch (Exception e) {// TODO Auto-generated catch block e.printStackTrace();}}
?