java中GET方式提交的示例:
/** * 获取关注列表; * @return */ @SuppressWarnings("unchecked") public static ArrayListgetUserList() { StringBuffer bufferRes = new StringBuffer(); ArrayList 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 (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 ob_user = null; //大于1000需要多次获取,或许次数为count/1000 for(int i=0;i (ob_data.getJSONArray("openid")); for(String open_id : ob_user){ //将多次获取的openid添加到同一个数组 users.add(open_id); } } } } return users; }
java中POST方式提交的示例1:
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
post请求向服务器传递参数的另外一种形式,示例2:
服务器端接受参数:String datas= request.getParameter("datas");
public static void sendPost() throws IOException{ List> list = new ArrayList >(); Map map = new HashMap (); 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);
in.close(); out.close();
} catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
接收数据服务器上接收数据的方式,示例1:
@RequestMapping(value = "/synSystemData") public void synSystemData(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean isGet = request.getMethod().toLowerCase().equals("get"); if (!isGet) { String inputLine; String notityJson = ""; try { while ((inputLine = request.getReader().readLine()) != null) { notityJson += inputLine; } request.getReader().close(); } catch (Exception e) { e.printStackTrace(); } if(StringUtil.isEmpty(notityJson )){ notityJson = request.getParameter("content"); } String json= java.net.URLDecoder.decode(notityJson , "UTF-8"); if(StringUtils.isNotEmpty(json)){ StringBuffer sb = new StringBuffer(); sb.append("ok"); response.getWriter().write(sb.toString()); } } wirte.flush(); wirte.close(); }
接收数据服务器上接收数据的方式,示例2:
/** * 接收从发送数据服务器传过来的json串 * @param request * @param response * @throws Exception */ @RequestMapping(value = "/synSystemData") public void synSystemData(HttpServletRequest request, HttpServletResponse response) throws Exception{ String result = "error"; boolean isPost = request.getMethod().toLowerCase().equals("post"); PrintWriter wirte = null; wirte = response.getWriter(); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); if (isPost) { String json = request.getParameter("datas"); System.out.println(json); wirte.print(result); }else{ wirte.print(""); } wirte.flush(); wirte.close(); }