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/1000 for(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方式提交的示例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<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请求向服务器传递参数的另外一种形式,示例2:

服务器端接受参数: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);
        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();
}

java中GET方式提交和POST方式提交的更多相关文章

  1. JAVA中单例模式的几种实现方式

    1 线程不安全的实现方法 首先介绍java中最基本的单例模式实现方式,我们可以在一些初级的java书中看到.这种实现方法不是线程安全的,所以在项目实践中如果涉及到线程安全就不会使用这种方式.但是如果不 ...

  2. Java中HashMap遍历的两种方式

    Java中HashMap遍历的两种方式 转]Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml 第一种: ...

  3. JAVA中集合输出的四种方式

    在JAVA中Collection输出有四种方式,分别如下: 一) Iterator输出. 该方式适用于Collection的所有子类. public class Hello { public stat ...

  4. java中数组复制的两种方式

    在java中数组复制有两种方式: 一:System.arraycopy(原数组,开始copy的下标,存放copy内容的数组,开始存放的下标,需要copy的长度); 这个方法需要先创建一个空的存放cop ...

  5. JAVA中的四种JSON解析方式详解

    JAVA中的四种JSON解析方式详解 我们在日常开发中少不了和JSON数据打交道,那么我们来看看JAVA中常用的JSON解析方式. 1.JSON官方 脱离框架使用 2.GSON 3.FastJSON ...

  6. Java 中UDP原理机制及实现方式介绍(建议阅读者阅读前了解下Java的基础知识,一方便理解)

    1.基本概念介绍: 首先得简单介绍下UDP. UDP( User Datagram Protocol )协议是用户数据报,在网络中它与TCP协议一样用于处理数据包.在OSI模型中,在第四层——传输层, ...

  7. Java中String对象两种赋值方式的区别

    本文修改于:https://www.zhihu.com/question/29884421/answer/113785601 前言:在java中,String有两种赋值方式,第一种是通过“字面量”赋值 ...

  8. Java中创建线程的三种方式以及区别

    在java中如果要创建线程的话,一般有3种方法: 继承Thread类: 实现Runnable接口: 使用Callable和Future创建线程. 1. 继承Thread类 继承Thread类的话,必须 ...

  9. Java中实现多线程的两种方式之间的区别

    Java提供了线程类Thread来创建多线程的程序.其实,创建线程与创建普通的类的对象的操作是一样的,而线程就是Thread类或其子类的实例对象.每个Thread对象描述了一个单独的线程.要产生一个线 ...

  10. 细说java中Map的两种迭代方式

    曾经对java中迭代方式总是迷迷糊糊的,今天总算弄懂了.特意的总结了一下.基本是算是理解透彻了. 1.再说Map之前先说下Iterator: Iterator主要用于遍历(即迭代訪问)Collecti ...

随机推荐

  1. react+redux+generation-modation脚手架搭建一个todolist

    TodoList 1. 编写actions.js 2. 分析state 试着拆分成多个reducer 3. 了解store 4. 了解redux数据流生命周期 5. 分析容器组件和展示组件 搞清楚,数 ...

  2. 前端必备工具-Emmet (Zen Coding)

    Emmet 可以快速的编写 HTML 和 CSS,输入指令如: ul#nav>li*4>a*4 敲击一下TAB 键,就会输出: <ul id="nav"> ...

  3. Linux C/C++开发工具

    1. vim + ctags + taglist + cscope + cppcomplete + global 2.emacs+插件 可以查看 http://blog.163.com/yu_hong ...

  4. 关于Gson在强转时的ClassCastException

    关于Gson的坑人指出: 将list转化为json String beanListToJson = gson.toJson(list, type); 将json还原为list List<T &g ...

  5. 如何安装pip、升级pip包。mac下安装包的路径

    参考:https://pip.pypa.io/en/stable/installing/ 1.wget -c  https://bootstrap.pypa.io/get-pip.py 2.pytho ...

  6. 5 cocos2dx 3.0源码分析 渲染 render

    渲染,感觉这个挺重要了,这里代入一个简单的例子 Sprite 建立及到最后的画在屏幕上, 我们描述一下这个渲染的流程:   1 sprite 初始化(纹理, 坐标,及当前元素的坐标大小信息) 2 主循 ...

  7. C#常见算法题目

        //冒泡排序    public class bubblesorter    {        public void sort(int[] list)        {            ...

  8. 切线空间(Tangent Space)法线映射(Normal Mapping)【转】

    // 请注明出处:http://blog.csdn.net/BonChoix,谢谢~) 切线空间(Tangent Space) 切换空间,同局部空间.世界空间等一样,是3D图形学中众多的坐标系之一.切 ...

  9. MapReduce 编程模型概述

    MapReduce 编程模型给出了其分布式编程方法,共分 5 个步骤:1) 迭代(iteration).遍历输入数据, 并将之解析成 key/value 对.2) 将输入 key/value 对映射( ...

  10. windows10 Sqlserver卸载 指定账户不存在

    在windows卸载程序时,有时会出现因提示“指定的账户不存在”而无法删除,如下: 这时时候要先选择要删除的项目,进行修复后再进行删除就可以正常删除了