Object转JSON字符串: String jsonStr = JSONObject.toJSONString(object); JSON字符串转JSONObject: JSONObject jsonObject = JSONObject.parseObject(jsonStr); JSON字符串转Object对象 T t = JSON.parseObject(jsonStr,T.class); —–注:JSON字符串是有格式要求的,必须为键值对形式,不是任意的字符串。—– ——————— 作者:KnifeBlade 来源:CSDN 原文:https://blog.csdn.net/qq_29468573/article/details/82190005
View Details在使用fastjson进行数据类型转换时发现,pojo类里面的属性首字母大写,在转成json之后,变成了小写。导致数据存储一直有问题。 转换之后结果为: 导致数据存储失败。(使用json传值进行持久化操作。) 解决方法: 在pojo类的属性get方法上加上你需要的key。 这样转换的json,对应的key就改变为你注解对应的属性名。 from:https://blog.csdn.net/cuuuc233/article/details/80983486
View DetailsJSONObject.toJSONString(Object object, SerializerFeature… features) Fastjson的SerializerFeature序列化属性 QuoteFieldNames———-输出key时是否使用双引号,默认为true WriteMapNullValue——–是否输出值为null的字段,默认为false WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非nul
1 2 3 4 5 6 7 8 9 |
Map < String , Object > jsonMap = new HashMap< String , Object>(); jsonMap.put("a",1); jsonMap.put("b",""); jsonMap.put("c",null); jsonMap.put("d","dddddddddd"); String str = JSONObject.toJSONString(jsonMap,SerializerFeature.WriteMapNullValue); System.out.println(str); //输出结果:{"a":1,"b":"","c":null,"d":"dddddddddd"} |
from:http://www.voidcn.com/article/p-ebkhpvlq-bqh.html
View DetailsRestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
我之前的HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,稍微截个图,这是我封装好的一个post请求工具:
本教程将带领大家实现Spring生态内RestTemplate的Get请求和Post请求还有exchange指定请求类型的实践和RestTemplate核心方法源码的分析,看完你就会用优雅的方式来发HTTP请求。
View DetailsHttp请求类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); e.printStackTrace(); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ ex.printStackTrace(); } } return result; } } |
调用方法:
1 2 3 4 5 6 7 8 9 |
public static void main(String[] args) { //发送 GET 请求 String s=HttpRequest.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456"); System.out.println(s); //发送 POST 请求 String sr=HttpRequest.sendPost("http://localhost:6144/Home/RequestPostString", "key=123&v=456"); System.out.println(sr); } |
from:https://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html
View Detailspom配置 html内容 1 通过注解 1.1 在properties文件下配置属性 1.2 利用@Value注解将对应的属性注入到field上 1.3 请求结果如下 2 通过PropertiesLoaderUtils 利用org.springframework.core.io.support包下的PropertiesLoaderUtils读取配置文件从而获得对应的配置信息 PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource(location), "UTF-8")); 将对应配置文件的信息填入location即可 2.1 在properties文件下配置属性 2.2 创建工具类 2.3 读取配置信息 2.4 请求结果如下 3 通过@PropertySource将属性映射给类的属性 3.1 配置属性 3.2 属性映射 3.3 请求结果 4 利用Environment (org.springframework.core.env.Environment) 4.1 配置属性 4.2 引入Environment 4.3 请求结果 from:https://www.cnblogs.com/zad27/p/10483484.html
View Details目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现。HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,HttpClient3.1 是 org.apache.commons.httpclient下操作远程 url的工具包,虽然已不再更新,但实现工作中使用httpClient3.1的代码还是很多,HttpClient4.5是org.apache.http.client下操作远程 url的工具包,最新的;另一种则是通过HttpURLConnection去实现,HttpURLConnection是JAVA的标准类,是JAVA比较原生的一种实现方式。 自己在工作中三种方式都用到过,总结一下分享给大家,也方便自己以后使用,话不多说上代码。 第一种方式:java原生HttpURLConnection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
package com.powerX.httpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpClient { public static String doGet(String httpurl) { HttpURLConnection connection = null; InputStream is = null; BufferedReader br = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(httpurl); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(60000); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 封装输入流is,并指定字符集 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); // 存放数据 StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } connection.disconnect();// 关闭远程连接 } return result; } public static String doPost(String httpUrl, String param) { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 通过连接对象获取一个输出流 os = connection.getOutputStream(); // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 os.write(param.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); sbf.append("\r\n"); } result = sbf.toString(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 断开与远程地址url的连接 connection.disconnect(); } return result; } } |
第二种方式:apache HttpClient3.1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
package com.powerX.httpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpClient3 { public static String doGet(String url) { // 输入流 InputStream is = null; BufferedReader br = null; String result = null; // 创建httpClient实例 HttpClient httpClient = new HttpClient(); // 设置http连接主机服务超时时间:15000毫秒 // 先获取连接管理器对象,再获取参数对象,再进行参数的赋值 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); // 创建一个Get方法实例对象 GetMethod getMethod = new GetMethod(url); // 设置get请求超时为60000毫秒 getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反 getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); try { // 执行Get方法 int statusCode = httpClient.executeMethod(getMethod); // 判断返回码 if (statusCode != HttpStatus.SC_OK) { // 如果状态码返回的不是ok,说明失败了,打印错误信息 System.err.println("Method faild: " + getMethod.getStatusLine()); } else { // 通过getMethod实例,获取远程的一个输入流 is = getMethod.getResponseBodyAsStream(); // 包装输入流 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); // 读取封装的输入流 String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp).append("\r\n"); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 释放连接 getMethod.releaseConnection(); } return result; } public static String doPost(String url, Map<String, Object> paramMap) { // 获取输入流 InputStream is = null; BufferedReader br = null; String result = null; // 创建httpClient实例对象 HttpClient httpClient = new HttpClient(); // 设置httpClient连接主机服务器超时时间:15000毫秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); // 创建post请求方法实例对象 PostMethod postMethod = new PostMethod(url); // 设置post请求超时时间 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); NameValuePair[] nvp = null; // 判断参数map集合paramMap是否为空 if (null != paramMap && paramMap.size() > 0) {// 不为空 // 创建键值参数对象数组,大小为参数的个数 nvp = new NameValuePair[paramMap.size()]; // 循环遍历参数集合map Set<Entry<String, Object>> entrySet = paramMap.entrySet(); // 获取迭代器 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); int index = 0; while (iterator.hasNext()) { Entry<String, Object> mapEntry = iterator.next(); // 从mapEntry中获取key和value创建键值对象存放到数组中 try { nvp[index] = new NameValuePair(mapEntry.getKey(), new String(mapEntry.getValue().toString().getBytes("UTF-8"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } index++; } } // 判断nvp数组是否为空 if (null != nvp && nvp.length > 0) { // 将参数存放到requestBody对象中 postMethod.setRequestBody(nvp); } // 执行POST方法 try { int statusCode = httpClient.executeMethod(postMethod); // 判断是否成功 if (statusCode != HttpStatus.SC_OK) { System.err.println("Method faild: " + postMethod.getStatusLine()); } // 获取远程返回的数据 is = postMethod.getResponseBodyAsStream(); // 封装输入流 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; while ((temp = br.readLine()) != null) { sbf.append(temp).append("\r\n"); } result = sbf.toString(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 释放连接 postMethod.releaseConnection(); } return result; } } |
第三种方式:apache httpClient4.5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
package com.powerX.httpClient; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClient4 { public static String doGet(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { // 通过址默认配置创建一个httpClient实例 httpClient = HttpClients.createDefault(); // 创建httpGet远程连接实例 HttpGet httpGet = new HttpGet(url); // 设置请求头信息,鉴权 httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0"); // 设置配置请求参数 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 请求超时时间 .setSocketTimeout(60000)// 数据读取超时时间 .build(); // 为httpGet实例设置配置 httpGet.setConfig(requestConfig); // 执行get请求得到返回对象 response = httpClient.execute(httpGet); // 通过返回对象获取返回数据 HttpEntity entity = response.getEntity(); // 通过EntityUtils中的toString方法将结果转换为字符串 result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != response) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static String doPost(String url, Map<String, Object> paramMap) { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; String result = ""; // 创建httpClient实例 httpClient = HttpClients.createDefault(); // 创建httpPost远程连接实例 HttpPost httpPost = new HttpPost(url); // 配置请求参数实例 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 设置连接请求超时时间 .setSocketTimeout(60000)// 设置读取数据连接超时时间 .build(); // 为httpPost实例设置配置 httpPost.setConfig(requestConfig); // 设置请求头 httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); // 封装post请求参数 if (null != paramMap && paramMap.size() > 0) { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); // 通过map集成entrySet方法获取entity Set<Entry<String, Object>> entrySet = paramMap.entrySet(); // 循环遍历,获取迭代器 Iterator<Entry<String, Object>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<String, Object> mapEntry = iterator.next(); nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString())); } // 为httpPost设置封装好的请求参数 try { httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } try { // httpClient对象执行post请求,并返回响应参数对象 httpResponse = httpClient.execute(httpPost); // 从响应对象中获取响应内容 HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } } |
有时候我们在使用post请求时,可能传入的参数是json或者其他格式,此时我们则需要更改请求头及参数的设置信息,以httpClient4.5为例,更改下面两列配置:httpPost.setEntity(new StringEntity("你的json串")); httpPost.addHeader("Content-Type", "application/json")。 from:https://www.cnblogs.com/hhhshct/p/8523697.html
View Details本文来自:https://www.sojson.com/blog/350.html 以前我们创建一个Http请求,很复杂,要写很多代码,而且请求还有各种兼容问题。而用 RestTemplate 的话优雅的几行代码就可以解决,并且是可以直接返回对象。 RestTemplate 是 Spring 用于同步请求client端的核心类,简化了与 HTTP 的通信,并满足RestFul原则,RestTemplate默认依赖 JDK 的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP 数据源,比如Apache HttpComponents、Netty和OkHttp,都是支持的。 HTTP Get 请求 我们先做一个普通的Http请求,直接上源码。
1 2 3 4 5 6 7 8 9 10 11 12 |
try { HttpClient client = new HttpClient(); //创建一个Get请求 GetMethod method = new GetMethod("http://t.weather.sojson.com/api/weather/city/"+101010100); client.executeMethod(method); //获取String类型的返回值 String res = method.getResponseBodyAsString(); //使用gson转换为对象 WeatherDto dto = new Gson().fromJson(res,WeatherDto.class); } catch (IOException e) { e.printStackTrace(); } |
这是一个最简单的Http请求,把返回值使用 Gson 来转换成对象。 使用RestTemplate HTTP Get 请求
1 2 |
RestTemplate restTemplate = new RestTemplate(); WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/"+101010100 , WeatherDto.class); |
上面其实是一个简单的带参数请求,用“{1}”、“{2}”、“{3}”… 方式传参,如果是地址拼接的方式,可以N个。 上一篇博客采用这个方式,模拟的Http请求,请求天气接口数据:https://www.sojson.com/blog/349.html 。 2.RestTemplate 多个参数请求 因为是Get请求,其实就是问号的方式带参数请求
1 2 3 4 |
Map<String,String> map = new HashMap(); map.put("id",101010100); RestTemplate restTemplate = new RestTemplate(); Details detail = restTemplate.getForObject("http://example.sojson.com/detail.html" , Details.class,map); |
3.RestTemplate getForEntity 请求 其实上面的1和2算是简单的请求,就是直接返回了Object 实例对象。而我们要获取详细的详细,如返回status、Header信息等。那就得用 getForEntity 。 看看源码里的参数描述,其实是和 getForObject 一致,我这里网络不行没下载下来源码包,凑合看看。
1 2 3 4 5 |
<T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Object... var3) throws RestClientException; <T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException; <T> ResponseEntity<T> getForEntity(URI var1, Class<T> var2) throws RestClientException; |
HTTP 实例讲解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
RestTemplate restTemplate = new RestTemplate(); String url = "http://example.sojson.com/detail.html"; //添加请求头 HttpHeaders headers = new HttpHeaders(); //form表单提交 application/x-www-form-urlencoded headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //组装参数 MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "101010100"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<WeatherDto> response = restTemplate.postForEntity( url, request , WeatherDto.class ); //返回对象 WeatherDto dto = response.getBody(); //HTTP状态 int status = response.getStatusCodeValue(); //Spring 封装的 HttpStatus statusCode = response.getStatusCode(); //封装的对应状态请求,返回来都是 Boolean 类型 statusCode.is2xxSuccessful();//2开头的成功状态 statusCode.is3xxRedirection();//3开头重定向 statusCode.is4xxClientError();//4开头客户端错误 statusCode.is5xxServerError();//5开头服务端异常 |
具体可以自行测试下。 我们看源码知道还有 Post请求 方法。
1 2 |
restTemplate.postForEntity( ... ) restTemplate.postForObject(... ) |
方法传参是和上面讲解的 Get请求 的使用方式一模一样。 有兴趣的可以测试下我们的在线 HTTP模拟请求 工具 ,就是采用 restTemplate 实现的。 HTTP在线模拟请求 from:https://cloud.tencent.com/developer/article/1554561
View Details1.用户登录请求登录接口时,验证用户名密码等,验证成功会返回给前端一个token,这个token就是之后鉴权的唯一凭证。
2.后台可能将token存储在redis或者数据库中。
3.之后前端的请求,需要在header中携带token,后端取出token去redis或者数据库中进行验证,如果验证通过则放行,如果不通过则拒绝操作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class UnixDateTimeConvertor : DateTimeConverterBase { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return DateTime.Parse(reader.Value.ToString()); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { //System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); //long timeStamp = (long)(((DateTime)value) - startTime).TotalMilliseconds; writer.WriteValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss")); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 //GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter //{ // DateTimeFormat = "yyyy-MM-dd HH:mm:ss" //}); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); //设置Datetime 到 時間戳 的互轉 JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings() { Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Local }; jSettings.Converters.Add(new UnixDateTimeConvertor()); config.Formatters.JsonFormatter.SerializerSettings = jSettings; } } |
from:https://www.cnblogs.com/liuqiyun/p/10729338.html
View Details