服务端PHP代码可以从这里下载:https://github.com/lornajane/PHP-Web-Services

1.使用volley实现:

request要用JsonObjectRequest,这个request在url后面带有一个JSONObject类型的参数

如果服务端有检测http头的请求数据类型和接受数据类型(比如有的服务端会根据http头中的Accept字段标示的类型,返回json,xml或其他数据类型,也会根据Content-type字段的标示,按json或form类型解析请求参数),还需要在getHeaders回调中设置头部参数,如果服务端不检测,可以不设置:

 headers.put("Accept", "application/json");//表示接受json类型的响应
 headers.put("Content-Type", "application/json; charset=UTF-8");//表示传递给服务器的参数是json类型

String strUrl = "http://10.2.152.133/test/rest/rest.php/items";
try {
    JSONObject jsonBody = new JSONObject("{\"name\":\"Brett\",\"link\":\"haha\"}");

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
            strUrl, jsonBody, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("qf", response.toString());
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("qf", error.getMessage());
                }
            }

    ) {
        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json; charset=UTF-8");

            return headers;
        }
    };

    MyApp.mRequestQueue.add(request);
} catch (Exception e) {
    e.printStackTrace();
}

2.使用httputils实现:

content-type设置也要根据情况需要,同volley一样

普通的表单请求是addQueryStringParameter(get)或addBodyParameter(post),json请求是setBodyEntity

protected void postJsonByXutils() {
    String strUrl = "http://10.2.152.133/test/rest/rest.php/items";
    RequestParams requestParams = new RequestParams();
    requestParams.addHeader("Content-Type", "applicasettion/json");

    JSONObject json = new JSONObject();

    try {
        json.put("name", "zy");
        json.put("link", "zy2");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    requestParams.setBodyEntity(new StringEntity(json.toString(), "utf-8"));

    MyApp.mHttpUtils.send(HttpRequest.HttpMethod.POST,
            strUrl,requestParams,new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String strResult = responseInfo.result;
                    Log.d("qf", strResult);
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    Log.d("qf", msg);
                }
            });
}

3.使用httpurlconnection:

    protected void postJsonByHttpURLConnection() {
        HttpURLConnection httpcon;
        String url = "http://10.2.152.133/test/rest/rest.php/items";
        String data = "{\"name\":\"Brett2\",\"link\":\"haha2\"}";
        String result = null;
        try {
//Connect
            httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
            httpcon.setDoOutput(true);
            httpcon.setRequestProperty("Content-Type", "application/json");
            httpcon.setRequestProperty("Accept", "application/json");
            httpcon.setRequestMethod("POST");
            httpcon.connect();

//Write
            OutputStream os = httpcon.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(data);
            writer.close();
            os.close();

//Read
            BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));

            String line = null;
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            br.close();
            result = sb.toString();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//http://blog.csdn.net/lamp_zy/article/details/52300629
    }//特别注意一点,在进行接口调用时,会发生乱码 connection.setRequestProperty("ContentType", "utf-8"); // 设置发送数据的格式   connection.setRequestProperty("Accept-Charset", "utf-8"); 

Json格式的http请求的更多相关文章

  1. Loadrunner:LR提交JSON格式的POST请求

    场景: 影视分发:影院客户端向管理平台发起取任务的操作,取任务接口getDispatchTask,为JSON格式的POST请求 Action() { web_custom_request(" ...

  2. requests(一): 发送一个json格式的post请求

    今天给一位同学解决post发送数据格式为json格式的请求,顺便确认一下问题归属. 背景: 用postman工具发送一个数据格式为json的请求,得到了服务器的响应. 用python的requests ...

  3. python接口之request测试:以json格式发送post请求,.json方法,查看响应结果的情况

    json和dict python中的dict类型要转换为json格式的数据需要用到json库: import json <json> = json.dumps(<dict>) ...

  4. java发送application/json格式的post请求,需要登陆

    package util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWri ...

  5. java代码发送JSON格式的httpPOST请求

    package com.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOE ...

  6. postman发送json格式的post请求

    在地址栏里输入请求url:http://127.0.0.1:8081/getmoney 选择“POST”方式, 在“headers”添加key:Content-Type  , value:applic ...

  7. (转)java代码发送JSON格式的httpPOST请求

    import Java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import j ...

  8. SpringCloud中接收application/json格式的post请求参数并转化为实体类

    @CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod ...

  9. RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息

    原文地址:  http://www.cnblogs.com/hujunzheng/p/6018505.html RestTemplate发送请求并携带header信息   v1.使用restTempl ...

随机推荐

  1. 在birt中解决引用了不存在的绑定出现的问题

    在birt中常出现这个错误,xxx引用了不存在的绑定. 当你选中整个表,然后在下方属性编辑器旁边的绑定中可以看到绑定的字段.不需要的就可以删掉.也可以进行编辑. 想对查出来的数据加条件.可以选中数据明 ...

  2. 关于——NSThread

    创建.启动线程 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil] ...

  3. iOS中忽略NSLog打印信息(通过PCH文件中定义DEBUG宏解决)

    iOS中忽略NSLog打印信息 解决办法: 1.新建PrefixHeader_pch文件,在该文件中定义一下宏 //通过DEBUG宏的定义来解决Debug状态下和Release状态下的输出 #ifde ...

  4. Revenge of Fibonacc

    算法:搜索: In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence rela ...

  5. 直接拨号、将电话号码传入拨号程序、调用拨号程序、调用系统浏览器浏览网页、调用系统程序查看联系人、显示系统设置界面和显示Wi-Fi设置界面代码

    直接拨号.将电话号码传入拨号程序.调用拨号程序.调用系统浏览器浏览网页.调用系统程序查看联系人.显示系统设置界面和显示Wi-Fi设置界面代码 拨打号码的代码如下: Intent callIntent= ...

  6. kafka教程

    一.理论介绍(一)相关资料1.官方资料,非常详细:   http://kafka.apache.org/documentation.html#quickstart2.有一篇翻译版,基本一致,有些细节不 ...

  7. Debian/Ubuntu手动编译安装MongoDB C++11驱动及驱动测试

    本文章仅限cnblogs网站内转载!请某网站自觉,遵纪守法,尊重原创! 系统环境情况: 最小化.无桌面环境 新安装的Debian 8 Server 版本操作系统虚拟机一台 手动编译安装MongoDB ...

  8. jquery radio取值,checkbox取值,select取值,radio选中,checkbox选中,select选中

    jQuery获取Select选择的Text和Value: 语法解释: 1. $("#select_id").change(function(){//code...}); //为Se ...

  9. Vxworks、QNX、Xenomai、Intime、Sylixos、Ucos等实时操作系统的性能特点

    Vxworks.QNX.Xenomai.Intime.Sylixos.Ucos等实时操作系统的性能特点 VxWorks操作系统 VxWorks 操作系统是美国WindRiver公司于1983年设计开发 ...

  10. 简单讲解iOS应用开发中的MD5加密的相关使用

      简单讲解iOS应用开发中的MD5加密的相关使用   作者:文顶顶 字体:[增加 减小] 类型:转载 时间:2015-12-19 我要评论 这篇文章主要介绍了iOS应用开发中的MD5加密的相关使用, ...