博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Okhttp 向服务器发送请求(请求头,表单,post json数据) ...
阅读量:5889 次
发布时间:2019-06-19

本文共 5833 字,大约阅读时间需要 19 分钟。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qingfeng812/article/details/52130861
项目地址:https://github.com/Arisono/Gradle-demo
 
/**	 * @desc:post json数据提交   Header+params+json	 */	@SuppressWarnings("deprecation")	public static void sendHeadersAndJSON() {		// 表单提交 这种能满足大部分的需求		RequestBody formBody = new FormBody.Builder()				.add("jsonData", "{\"data\":\"121\",\"data1\":\"2232\"}")				.add("username", "Arison+中文").add("password", "1111111")				.build();		String postBody = "{\"type\":\"post json提交\"}";		String postBody2 = "{\"type2\":\"post json提交\"}";		OkHttpClient client = new OkHttpClient();		Request request = new Request.Builder()				.url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")				.header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")				.addHeader("content-type", "application/json;charset:utf-8")				.addHeader("Home", "china")// 自定义的header				.addHeader("user-agent", "android")				// .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))				.post(formBody)				// 表单提交				.put(RequestBody.create(						MediaType.parse("application/json; charset=utf-8"),						postBody))// post json提交				.put(RequestBody.create(						MediaType.parse("application/json; charset=utf-8"),						postBody2))// post json提交				.build();		try {			Response response = client.newCall(request).execute();			if (response.isSuccessful()) {				String json = response.body().string();				System.out.println(json);				String post = JSON.parseObject(json).getString("postBody");				System.out.println("转义之前:" + post);				System.out.println("转义之后:" + URLDecoder.decode(post));			}		} catch (IOException e) {			e.printStackTrace();		}	}	/**	 * @desc:发送请求头以及请求参数 Header+params	 */	public static void sendHeadersAndParams() {		String china_str = "";		try {			china_str = URLEncoder.encode("中文", "UTF-8");		} catch (UnsupportedEncodingException e1) {			e1.printStackTrace();		}		// 表单提交		RequestBody formBody = new FormBody.Builder().add("query", "Hello")				.add("username", "Arison").add("password", "1111111").build();		// 第二个表单会覆盖第一个		/*		 * RequestBody formBody2 = new FormBody.Builder() .add("search",		 * "Jurassic Park") .build();		 */		OkHttpClient client = new OkHttpClient();		Request request = new Request.Builder()				.url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")				.header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")				.addHeader("content-type", "text/html;charset:utf-8")				.addHeader("Home", "china")// 自定义的header				.addHeader("Home1", china_str)// 自定义的header 传中文				.addHeader("user-agent", "android")				// .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))				.post(formBody)				// .post(formBody2)				.build();		try {			Response response = client.newCall(request).execute();			if (response.isSuccessful()) {				String json = response.body().string();				System.out.println(json);			}		} catch (IOException e) {			e.printStackTrace();		}	}	/**	 * @desc:发送请求头	 */	public static void sendHeaders() {		String china_str = "";		try {			china_str = URLEncoder.encode("中文", "UTF-8");		} catch (UnsupportedEncodingException e1) {			e1.printStackTrace();		}		OkHttpClient client = new OkHttpClient();		Request request = new Request.Builder()				.url("http://localhost:8080/spring-mvc-showcase/api/getHeaders")				.header("cookie", "JSESSIONID=EB36DE5E50E342D86C55DAE0CDDD4F6D")				.addHeader("content-type", "text/html;charset:utf-8")				.addHeader("Home", "china")// 自定义的header				.addHeader("Home1", china_str)// 自定义的header 传中文				.addHeader("user-agent", "android").build();		try {			Response response = client.newCall(request).execute();			if (response.isSuccessful()) {				String json = response.body().string();				System.out.println(json);				String home1 = JSON.parseObject(json).getJSONObject("headers")						.getString("home1");				System.out.println(URLDecoder.decode(home1, "utf-8"));			}		} catch (IOException e) {			e.printStackTrace();		}	}	/**	 * @dec 基本测试	 * @throws IOException	 */	public static void sendBasicRequest() {		OkHttpClient client = new OkHttpClient();		Request request = new Request.Builder().url("http://www.baidu.com")				.build();		try {			Response response = client.newCall(request).execute();			if (!response.isSuccessful()) {				// throw new IOException("服务器端错误: " + response);			}			// 输入响应头			Headers responseHeaders = response.headers();			for (int i = 0; i < responseHeaders.size(); i++) {				System.out.println(responseHeaders.name(i) + ": "						+ responseHeaders.value(i));			}			// 输出响应实体			// System.out.println(response.body().string());		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}	}

服务器核心方法:

/**接收请求头	 * @return	 */	@RequestMapping(value = "/api/getHeaders")	private @ResponseBody LinkedHashMap
receiveHeaders( HttpServletRequest request, @CookieValue(value = "JSESSIONID", required = false) String sessionId,@RequestBody String postBody) { LinkedHashMap
result=new LinkedHashMap
(); Map
header=new HashMap
(); Map
params=new HashMap
(); result.put("postBody", postBody); @SuppressWarnings("rawtypes") Enumeration paramNames =request.getParameterNames(); while (paramNames.hasMoreElements()) { String key = (String) paramNames.nextElement(); Object value = request.getParameter(key); params.put(key, value); } result.put("params", params); @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); header.put(key, value); } result.put("headers", header); result.put("JSESSIONID", sessionId); System.out.println(result.toString()); return result; }
参考文档:

https://github.com/square/okhttp/wiki/Recipes

你可能感兴趣的文章
HTML5通信机制与html5地理信息定位(gps)
查看>>
加快ALTER TABLE 操作速度
查看>>
PHP 程序员的技术成长规划
查看>>
python基础教程_学习笔记19:标准库:一些最爱——集合、堆和双端队列
查看>>
js replace,正则截取字符串内容
查看>>
作业2
查看>>
nginx的信号量
查看>>
云im php,网易云IM
查看>>
c语言打开alist文件,C语言 文件的打开与关闭详解及示例代码
查看>>
DEFERRED_SEGMENT_CREATION
查看>>
Ada boost学习
查看>>
开源 java CMS - FreeCMS2.3字典管理
查看>>
block,inline和inline-block概念和区别
查看>>
移动端常见随屏幕滑动顶部固定导航栏背景色透明度变化简单jquery特效
查看>>
python基础---网络编程(socket编程)
查看>>
br-ex绑定的物理接口不能配置ip的原因
查看>>
centos6.x中fstab配置文件出错导致无法启动及忘记root密码解决方法
查看>>
Linux命令汇总
查看>>
C#静态类、静态构造函数,类与结构体的比较
查看>>
SVN+Gearman构建异步式代码分布系统
查看>>