Json格式的http请求
服务端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请求的更多相关文章
- Loadrunner:LR提交JSON格式的POST请求
场景: 影视分发:影院客户端向管理平台发起取任务的操作,取任务接口getDispatchTask,为JSON格式的POST请求 Action() { web_custom_request(" ...
- requests(一): 发送一个json格式的post请求
今天给一位同学解决post发送数据格式为json格式的请求,顺便确认一下问题归属. 背景: 用postman工具发送一个数据格式为json的请求,得到了服务器的响应. 用python的requests ...
- python接口之request测试:以json格式发送post请求,.json方法,查看响应结果的情况
json和dict python中的dict类型要转换为json格式的数据需要用到json库: import json <json> = json.dumps(<dict>) ...
- java发送application/json格式的post请求,需要登陆
package util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWri ...
- java代码发送JSON格式的httpPOST请求
package com.test; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOE ...
- postman发送json格式的post请求
在地址栏里输入请求url:http://127.0.0.1:8081/getmoney 选择“POST”方式, 在“headers”添加key:Content-Type , value:applic ...
- (转)java代码发送JSON格式的httpPOST请求
import Java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import j ...
- SpringCloud中接收application/json格式的post请求参数并转化为实体类
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod ...
- RestTemplate发送请求并携带header信息 RestTemplate post json格式带header信息
原文地址: http://www.cnblogs.com/hujunzheng/p/6018505.html RestTemplate发送请求并携带header信息 v1.使用restTempl ...
随机推荐
- webservice: Could not initialize Service NoSuchMethodException getPortClassMap()
今天用apache-cxf-3.1.1的wsdl2java生成webservice文件,调用的时候出了问题 报错:Could not initialize Service NoSuchMethodEx ...
- CentOS 6.3安装配置LAMP服务器(Apache+PHP5+MySQL)
准备篇: 1.配置防火墙,开启80端口.3306端口 vi /etc/sysconfig/iptables -A INPUT -m state --state NEW -m tcp -p tcp -- ...
- python爬虫程序
http://blog.csdn.net/pleasecallmewhy/article/details/8922826 此人的博客关于python爬虫程序分析得很好!
- 《python基础教程》笔记之 列表
list函数 list函数将其他类型的序列转换为列表,如 >>> list("hello world")['h', 'e', 'l', 'l', 'o', ' ' ...
- 设置tableWidget->verticalScrollBar()的属性
tableWidget->verticalScrollBar()->setStyleSheet("QScrollBar{background:rgb(255,255,0); wi ...
- 在VC中检测内存泄漏
声明:checkleaks.h和checkleaks.cpp这两个文件中的代码是在网上COPY的,但原来那个网站现在却找不到了 所以,这篇文章不算完全原创,呵呵. 就当作是一个存档吧 先上代码: // ...
- TCP粘包的拆包处理
因为TCP是流式处理的,所以包没有边界,必须设计一个包头,里面表示包的长度(一般用字节表示),根据这个来逐个拆包.如果对于发送/接收频率不高的话,一般也就不做拆包处理了,因为不大可能有粘包现象. 以下 ...
- 【转】C++读写二进制文件
原文网址:http://blog.csdn.net/lightlater/article/details/6364931 摘要: 使用C++读写二进制文件,在开发中操作的比较频繁,今天有幸找到一篇文章 ...
- delphi7开发webservice部属在apache服务器中 转
delphi7开发webservice部属在apache服务器中 delphi7 webservice apache 用Delphi7开发Web Service程序,并把服务程序放在apache We ...
- 【8】JAVA---地址App小软件(AddrDaoFile .class)(数据层)
实现数据进行文件的存储和读写. 本软件也就到此结束了. 没多少可以讲的. 因为这个小软件也就8个类,主要学习的也就是一个分层思想的简单应用. package cn.hncu.addr.dao; imp ...