Okhttp 向服务器发送请求(请求头,表单,post json数据)
来源:互联网 发布:同花顺mac版视频 编辑:程序博客网 时间:2024/05/23 22:55
项目地址: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 blocke.printStackTrace();}}
服务器核心方法:
/**接收请求头 * @return */@RequestMapping(value = "/api/getHeaders")private @ResponseBody LinkedHashMap<String, Object> receiveHeaders(HttpServletRequest request,@CookieValue(value = "JSESSIONID", required = false)String sessionId,@RequestBody String postBody) {LinkedHashMap<String, Object> result=new LinkedHashMap<String, Object>();Map<String, Object> header=new HashMap<String, Object>();Map<String, Object> params=new HashMap<String, Object>();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
0 0
- Okhttp 向服务器发送请求(请求头,表单,post json数据)
- c++ HTTP POST请求 向服务器发送json数据
- libcurl HTTP POST请求向服务器发送json数据
- post请求向服务器发送数据
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- iOS开发-post请求向服务器发送json格式数据(数组或字典)
- OkHttp之post请求发送给服务器json
- 如何向php服务器发送数据为json的post请求
- Android向Web服务器发送Post请求并返回数据
- Android向Web服务器发送Post请求并返回数据
- AJAX向服务器发送请求并返回json数据
- NSURLConnection 向服务器发送post请求
- okhttp发送post(json)请求数据,出现不走response.body().string(),单起一行打印的异常
- okhttp 网络请求添加请求头,get和post请求,表单提交 ,二进制流
- OkHttp请求json数据
- okhttp请求json数据
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android使用HttpClient以Post、Get请求服务器发送数据的方式(普通和json)
- Android- RelativeLayout属性
- 阿里云视频点播使用JavaScript上传文件重命名问题解决
- yii 应用组件
- 链表
- EventBus使用详解(一)——初步使用EventBus
- Okhttp 向服务器发送请求(请求头,表单,post json数据)
- 读取WEB-INF 下applicationContext.xml配置文件
- 2016-8-5Activity
- git初始化之gitconfig
- MySQL查询不区分大小写
- UIView中的坐标转换
- ubuntu下安装tomcat并注册服务
- 关于Project Tango项目 你需要知道的一切
- CodePush 热更新ReactNative之React Native Client SDK