版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29956725/article/details/87859544
OkHttp是一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,相对于Java的HttpClient使用起来更方便
首先导入SpringBoot需要依赖的jar包
1. 新建 OKHttpUtils类,里面包含了操作http的get,post 以及上传文件的操作类,为了方便测试,直接在这里面建了一个测试的类,用来进行测试
package cn.ok.http.utils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
/**
* 参考地址: http://www.cnblogs.com/nihaorz/p/5334208.html
* mockserver https://blog.csdn.net/heymysweetheart/article/details/52227379
* <p>
* 依赖的OKHtttp3 依赖的 maven jar包,因为OKHttp没有依赖的cookie包,所以采用OKHTTP3包
* <dependency>
* <groupId>com.squareup.okhttp3</groupId>
* <artifactId>okhttp</artifactId>
* <version>3.13.1</version>
* </dependency>
* 处理json相关的jar包
* <dependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>1.2.4</version>
* </dependency>
*/
public class OKHttpUtils {
private static OkHttpClient mOkHttpClient;
static {
httpClient();
}
public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException {
OKhttpTest.okHttpTest();
}
static OkHttpClient httpClient() {
mOkHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
//这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
return mOkHttpClient;
}
/**
* @param url 请求的url地址,如果还有params参数,则请求地址中必须是原始地址,不能再有参数
* @param header 请求的header参数,如果默认没有header参数,则设置为null即行
* @param params 请求的form表单参数,如果默认没有header参数,则设置为null即行
* @throws IOException
*/
static void httpGet(String url, Map<String, Object> header, Map<String, Object> params) throws IOException {
StringBuilder sb = new StringBuilder(url);
Request.Builder builder = new Request.Builder(); // .url(url);
Request request = null;
if (params != null) {
Boolean frist = true;
for (String key : params.keySet()) {
if (key != null && key.trim().length() > 0) {
if (url.contains("?")) {
throw new RuntimeException();
}
Object keyValue = params.get(key) == null ? "" : params.get(key);
sb.append(String.format("%s%s=%s", frist == true ? "?" : "&", key, keyValue));//构造get url 参数格式
frist = false;
}
}
}
builder.url(sb.toString());
if (header != null) {
for (String headerKey : header.keySet()) {
builder.addHeader(headerKey, header.get(headerKey).toString());
}
}
request = builder.build();
Response response = mOkHttpClient.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 content: " + response.body().string());
}
/**
* @param url
* @param json,如果json不存在,则传入为null
* @param requestType,必须传入
* @param header,请求头参数
* @throws IOException
*/
static void httpPost(String url, String json, Map<String, String> params, HTTP_CONTENT_TYPE requestType, Map<String, String> header) throws IOException {
if (requestType == null) {
throw new HttpException("请求类型必须传入不能为空", "400");
}
MediaType MEDIA_TYPE_TEXT = MediaType.parse(requestType.getContentType());
Request.Builder builder = new Request.Builder(); // .url(url);
Request request = null;
// json 请求
if (requestType.equals(HTTP_CONTENT_TYPE.APPLICATION_JSON)) {
if (json == null) {
json = "{}";
}
builder = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_TEXT, json));
}
// x-www-form-urlencoded 请求
if (requestType.equals(HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED)) {
FormBody.Builder formEncodingBuilder = new FormBody.Builder();
if (params != null) {
for (String key : params.keySet()) {
if (key != null && key.trim().length() > 0) {
String keyValue = params.get(key) == null ? "" : params.get(key);
formEncodingBuilder.add(key, keyValue);
}
}
}
RequestBody formBody = formEncodingBuilder.build();
builder = new Request.Builder()
.url(url)
.post(formBody);
}
if (header != null) {
for (String headerKey : header.keySet()) {
builder.addHeader(headerKey, header.get(headerKey).toString());
}
}
request = builder.build();
Response response = mOkHttpClient.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("response:" + responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println("response content: " + response.body().string());
}
/**
* @param url
* @param filePath
* @param fileName multipart/form-data 格式的请求,未进行封装
* @throws IOException
*/
static void httpPostFormDate(String url, String filePath, String fileName, String fileUpLoadPath) throws IOException {
String file = filePath + "\\" + fileName;
System.out.println("file is :" + file);
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"fileUpLoadPath\""), //指的是其他form表单的值的key
RequestBody.create(null, fileUpLoadPath)) //指的是其他form表单的值的value
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"" + fileName + "\""), //file指的是@RequestParam("file") MultipartFile file中的 file的名称,
RequestBody.create(MEDIA_TYPE_PNG, new File(file)))
.build();
Request request = new Request.Builder().url(url).post(requestBody).build(); // .url(url);
Response response = mOkHttpClient.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("response:" + responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println("response content: " + response.body().string());
}
}
enum HTTP_CONTENT_TYPE {
APPLICATION_X_WWW_FORM_URLENCODED("application/x-www-form-urlencoded;charset=utf-8"),
APPLICATION_JSON("application/json;charset=utf-8"),
MULTIPART_FORM_DATA("multipart/form-data");
private String contentType;
HTTP_CONTENT_TYPE(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
}
class HttpException extends RuntimeException {
private String statusCode;
private String message;
public HttpException(String message, String statusCode) {
super(message);
this.statusCode = statusCode;
}
}
class OKhttpTest {
static void okHttpGetTest() throws IOException {
OKHttpUtils.httpGet("http://localhost:6080/okHttp/request", null, null);
}
static void okHttpPostTest() throws IOException {
OKHttpUtils.httpPost("http://localhost:6080/okHttp/request", null, null, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
}
static void okHttpGetWithParamsTest() throws IOException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "lisi");
params.put("userAge", 50);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithParams", null, params);
}
static void okHttpPostWithParamsTest() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithParams", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
}
static void okHttpGetTestWithHeads() throws IOException {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithHeaders", headers, null);
}
static void okHttpPostTestWithHeads() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithHeaders", null, null, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, headers);
}
static void okHttpGetTestWithHeadsParams() throws IOException {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "lisi");
params.put("userAge", 50);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithHeadersAndParams", headers, params);
}
static void okHttpPostTestWithHeadsParams() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithHeadersAndParams", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, headers);
}
static void okHttpPostQueryByByJson() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
params.put("authorization_token", "authorization_token");
params.put("macAddress", "10.10.23.63");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/queryByByJson", JSON.toJSONString(params), params, HTTP_CONTENT_TYPE.APPLICATION_JSON, null);
}
static void okHttpSessionTest() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "zhagnsan");
params.put("passWord", "zhangsan@Pwd");
System.out.println("第一次未登录,则session相当于未空,所以无效");
OKHttpUtils.httpGet("http://localhost:6080/okHttp/sessionTimeOut", null, null);
System.out.println("第二次登录,则session相当于有效");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/sessionLogin", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/sessionTimeOut", null, null);
}
static void okHttpFileUpLoad() throws IOException {
String filePath = "D:\\Users\\source1"; //源文件路径
String fileUpLoadPath = "D:\\Users\\target1\\"; //上传文件路径
String fileName = "test.jpg";
OKHttpUtils.httpPostFormDate("http://localhost:6080/okHttp/uploadFile", filePath, fileName, fileUpLoadPath);
}
static void okHttpTest() throws InvocationTargetException, IllegalAccessException {
Method[] methodArr = OKhttpTest.class.getDeclaredMethods();
System.out.println(String.format("test--->begin all 需要总共测试%s个方法", methodArr.length - 1));
int i = 1;
for (Method method : methodArr) {
if (method.getName().equals("okHttpTest")) {
continue;
}
System.out.println(i + "." + "开始执行方法:" + method.getName() + ">>>>>>>>>>>");
method.invoke(null, null);
System.out.println(i + "." + "方法执行成功:" + method.getName() + "<<<<<<<<<<<" + "\n\n\n");
i++;
}
}
}
2. 新建Controller请求
package cn.ok.http.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.ok.http.utils.FileUtil;
@RestController
@RequestMapping("/okHttp")
public class OkHttpController {
@RequestMapping(value = "/request", method = { RequestMethod.GET, RequestMethod.POST })
public String request() {
return "index/index";
}
@RequestMapping(value = "requestWithHeaders",method = { RequestMethod.GET, RequestMethod.POST } )
String requestWithHeaders(@RequestHeader(value = "authorization_token", required = true) String token,
@RequestHeader(value = "mac_address", required = true) String macAddress) {
return String.format("authorization_token is %s, mac_address is %s", token, macAddress);
}
@RequestMapping(value = "/requestWithParams",method = { RequestMethod.GET,RequestMethod.POST } )
String requestWithParams(@RequestParam(value = "userName" ,required = true) String paramNameUser,
@RequestParam(value = "userAge" ,required = true) int paramAge) {
return String.format("paramNameUser is %s, paramAge is %s", paramNameUser, paramAge);
}
@RequestMapping(value = "/requestWithHeadersAndParams",method = { RequestMethod.GET,RequestMethod.POST } )
String requestWithHeadersAndParams( @RequestParam(value = "userName" ,required = true) String paramNameUser,
@RequestParam(value = "userAge" ,required = true) int paramAge,
@RequestHeader(value = "authorization_token", required = true) String token,
@RequestHeader(value = "mac_address", required = true) String macAddress
) {
return String.format("paramNameUser is %s, paramAge is %s,authorization_token is %s,mac_address is %s", paramNameUser, paramAge,token,macAddress);
}
@RequestMapping(value = "/queryByByJson",method = { RequestMethod.POST } )
public Object queryByTipper(@RequestBody Map<String,String> request) {
return request;
}
@RequestMapping(value = "/sessionLogin", method = RequestMethod.POST)
public Object sessionLogin (String userName,String passWord ,HttpServletRequest request){
Map<String ,String> user = new HashMap<String, String>();
user.put("userName",userName);
user.put("passWord",passWord);
request.getSession().setAttribute("sessionUser" ,user);
return user;
}
@RequestMapping(value = "/sessionTimeOut", method = RequestMethod.GET)
public Object sessionTimeOut (HttpServletRequest request){
if(request.getSession().getAttribute("sessionUser") == null) {
return "session为空,请重新登录";
}
return request.getSession().getAttribute("sessionUser");
}
@RequestMapping(value="/uploadFile", method = RequestMethod.POST)
public String uploadImg(@RequestParam("file") MultipartFile file,
@RequestParam(value = "fileUpLoadPath", required = true) String fileUpLoadPath,
HttpServletRequest request,HttpServletRequest response) {
String contentType = file.getContentType(); //图片文件类型
String fileName = UUID.randomUUID() + file.getOriginalFilename(); //图片名字
if(file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
return "上传文件不能为空";
}
Boolean fileEndWith =StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"jpg")
|| StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"png")
|| StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"jpeg");
if(BooleanUtils.isFalse(fileEndWith)){
return "上传文件格式不对,格式必须是jpg,png,jpeg,JPG,PNG,JPEG中的一种";
}
//调用文件处理类FileUtil,处理文件,将文件写入指定位置
try {
FileUtil.uploadFile(file.getBytes(), fileUpLoadPath, fileName);
} catch (Exception e) {
return "上传文件失败,请重新上传,错误信息为 " + e ;
}
// 返回图片的存放路径
return "上传成功,上传之后文件的fileName为" + fileName +"文件路径为:" + fileUpLoadPath ;
}
}
3. 新建FileUtils类:Controller类中上传文件会依赖FileUtils类
package cn.ok.http.utils;
import java.io.File;
import java.io.FileOutputStream;
public class FileUtil {
//文件上传工具类服务方法
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}
执行测试的结果为:
D:\develop\jdk\Jdk1.8.0.45\bin\java "-javaagent:D:\idea\ideaInstall\IntelliJ IDEA 2017.2.1\lib\idea_rt.jar=56446:D:\idea\ideaInstall\IntelliJ IDEA 2017.2.1\bin" -Dfile.encoding=UTF-8 -classpath D:\develop\jdk\Jdk1.8.0.45\jre\lib\charsets.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\deploy.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\access-bridge-64.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\cldrdata.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\dnsns.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\jaccess.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\jfxrt.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\localedata.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\nashorn.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\sunec.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\sunjce_provider.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\sunmscapi.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\sunpkcs11.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\ext\zipfs.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\javaws.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\jce.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\jfr.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\jfxswt.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\jsse.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\management-agent.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\plugin.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\resources.jar;D:\develop\jdk\Jdk1.8.0.45\jre\lib\rt.jar;D:\idea\workspace\okHttp\target\classes;D:\develop\mavenHouse\org\springframework\boot\spring-boot-starter-web\1.5.1.RELEASE\spring-boot-starter-web-1.5.1.RELEASE.jar;D:\develop\mavenHouse\org\springframework\boot\spring-boot-starter\1.5.1.RELEASE\spring-boot-starter-1.5.1.RELEASE.jar;D:\develop\mavenHouse\org\springframework\boot\spring-boot\1.5.1.RELEASE\spring-boot-1.5.1.RELEASE.jar;D:\develop\mavenHouse\org\springframework\boot\spring-boot-autoconfigure\1.5.1.RELEASE\spring-boot-autoconfigure-1.5.1.RELEASE.jar;D:\develop\mavenHouse\org\springframework\boot\spring-boot-starter-logging\1.5.1.RELEASE\spring-boot-starter-logging-1.5.1.RELEASE.jar;D:\develop\mavenHouse\ch\qos\logback\logback-classic\1.1.9\logback-classic-1.1.9.jar;D:\develop\mavenHouse\ch\qos\logback\logback-core\1.1.9\logback-core-1.1.9.jar;D:\develop\mavenHouse\org\slf4j\jcl-over-slf4j\1.7.22\jcl-over-slf4j-1.7.22.jar;D:\develop\mavenHouse\org\slf4j\jul-to-slf4j\1.7.22\jul-to-slf4j-1.7.22.jar;D:\develop\mavenHouse\org\slf4j\log4j-over-slf4j\1.7.22\log4j-over-slf4j-1.7.22.jar;D:\develop\mavenHouse\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;D:\develop\mavenHouse\org\hibernate\hibernate-validator\5.3.4.Final\hibernate-validator-5.3.4.Final.jar;D:\develop\mavenHouse\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;D:\develop\mavenHouse\org\jboss\logging\jboss-logging\3.3.0.Final\jboss-logging-3.3.0.Final.jar;D:\develop\mavenHouse\com\fasterxml\jackson\core\jackson-databind\2.8.6\jackson-databind-2.8.6.jar;D:\develop\mavenHouse\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;D:\develop\mavenHouse\com\fasterxml\jackson\core\jackson-core\2.8.6\jackson-core-2.8.6.jar;D:\develop\mavenHouse\org\springframework\spring-web\4.3.6.RELEASE\spring-web-4.3.6.RELEASE.jar;D:\develop\mavenHouse\org\springframework\spring-aop\4.3.6.RELEASE\spring-aop-4.3.6.RELEASE.jar;D:\develop\mavenHouse\org\springframework\spring-beans\4.3.6.RELEASE\spring-beans-4.3.6.RELEASE.jar;D:\develop\mavenHouse\org\springframework\spring-context\4.3.6.RELEASE\spring-context-4.3.6.RELEASE.jar;D:\develop\mavenHouse\org\springframework\spring-webmvc\4.3.6.RELEASE\spring-webmvc-4.3.6.RELEASE.jar;D:\develop\mavenHouse\org\springframework\spring-expression\4.3.6.RELEASE\spring-expression-4.3.6.RELEASE.jar;D:\develop\mavenHouse\com\alibaba\fastjson\1.2.4\fastjson-1.2.4.jar;D:\develop\mavenHouse\javax\servlet\javax.servlet-api\3.1.0\javax.servlet-api-3.1.0.jar;D:\develop\mavenHouse\javax\servlet\jstl\1.2\jstl-1.2.jar;D:\develop\mavenHouse\org\apache\tomcat\embed\tomcat-embed-core\8.5.11\tomcat-embed-core-8.5.11.jar;D:\develop\mavenHouse\org\apache\tomcat\embed\tomcat-embed-el\8.5.11\tomcat-embed-el-8.5.11.jar;D:\develop\mavenHouse\org\apache\tomcat\embed\tomcat-embed-jasper\8.5.11\tomcat-embed-jasper-8.5.11.jar;D:\develop\mavenHouse\org\eclipse\jdt\core\compiler\ecj\4.5.1\ecj-4.5.1.jar;D:\develop\mavenHouse\io\springfox\springfox-swagger2\2.6.1\springfox-swagger2-2.6.1.jar;D:\develop\mavenHouse\io\swagger\swagger-annotations\1.5.10\swagger-annotations-1.5.10.jar;D:\develop\mavenHouse\io\swagger\swagger-models\1.5.10\swagger-models-1.5.10.jar;D:\develop\mavenHouse\io\springfox\springfox-spi\2.6.1\springfox-spi-2.6.1.jar;D:\develop\mavenHouse\io\springfox\springfox-core\2.6.1\springfox-core-2.6.1.jar;D:\develop\mavenHouse\io\springfox\springfox-schema\2.6.1\springfox-schema-2.6.1.jar;D:\develop\mavenHouse\io\springfox\springfox-swagger-common\2.6.1\springfox-swagger-common-2.6.1.jar;D:\develop\mavenHouse\io\springfox\springfox-spring-web\2.6.1\springfox-spring-web-2.6.1.jar;D:\develop\mavenHouse\com\google\guava\guava\18.0\guava-18.0.jar;D:\develop\mavenHouse\com\fasterxml\classmate\1.3.3\classmate-1.3.3.jar;D:\develop\mavenHouse\org\slf4j\slf4j-api\1.7.22\slf4j-api-1.7.22.jar;D:\develop\mavenHouse\org\springframework\plugin\spring-plugin-core\1.2.0.RELEASE\spring-plugin-core-1.2.0.RELEASE.jar;D:\develop\mavenHouse\org\springframework\plugin\spring-plugin-metadata\1.2.0.RELEASE\spring-plugin-metadata-1.2.0.RELEASE.jar;D:\develop\mavenHouse\org\mapstruct\mapstruct\1.0.0.Final\mapstruct-1.0.0.Final.jar;D:\develop\mavenHouse\io\springfox\springfox-swagger-ui\2.6.1\springfox-swagger-ui-2.6.1.jar;D:\develop\mavenHouse\org\springframework\spring-core\4.3.6.RELEASE\spring-core-4.3.6.RELEASE.jar;D:\develop\mavenHouse\com\squareup\okhttp3\okhttp\3.13.1\okhttp-3.13.1.jar;D:\develop\mavenHouse\com\squareup\okio\okio\1.17.2\okio-1.17.2.jar;D:\develop\mavenHouse\commons-lang\commons-lang\2.6\commons-lang-2.6.jar cn.ok.http.utils.OKHttpUtils
test--->begin all 需要总共测试11个方法
1.开始执行方法:okHttpGetWithParamsTest>>>>>>>>>>>
Content-Type: text/plain;charset=UTF-8
Content-Length: 37
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: paramNameUser is lisi, paramAge is 50
1.方法执行成功:okHttpGetWithParamsTest<<<<<<<<<<<
2.开始执行方法:okHttpPostWithParamsTest>>>>>>>>>>>
response:Content-Type: text/plain;charset=UTF-8
response:Content-Length: 37
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: paramNameUser is lisi, paramAge is 50
2.方法执行成功:okHttpPostWithParamsTest<<<<<<<<<<<
3.开始执行方法:okHttpGetTestWithHeads>>>>>>>>>>>
Content-Type: text/plain;charset=UTF-8
Content-Length: 72
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: authorization_token is xysfafsxofweolxxepppp, mac_address is 10.10.23.63
3.方法执行成功:okHttpGetTestWithHeads<<<<<<<<<<<
4.开始执行方法:okHttpPostTestWithHeads>>>>>>>>>>>
response:Content-Type: text/plain;charset=UTF-8
response:Content-Length: 72
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: authorization_token is xysfafsxofweolxxepppp, mac_address is 10.10.23.63
4.方法执行成功:okHttpPostTestWithHeads<<<<<<<<<<<
5.开始执行方法:okHttpGetTestWithHeadsParams>>>>>>>>>>>
Content-Type: text/plain;charset=UTF-8
Content-Length: 109
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: paramNameUser is lisi, paramAge is 50,authorization_token is xysfafsxofweolxxepppp,mac_address is 10.10.23.63
5.方法执行成功:okHttpGetTestWithHeadsParams<<<<<<<<<<<
6.开始执行方法:okHttpPostTestWithHeadsParams>>>>>>>>>>>
response:Content-Type: text/plain;charset=UTF-8
response:Content-Length: 109
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: paramNameUser is lisi, paramAge is 50,authorization_token is xysfafsxofweolxxepppp,mac_address is 10.10.23.63
6.方法执行成功:okHttpPostTestWithHeadsParams<<<<<<<<<<<
7.开始执行方法:okHttpPostQueryByByJson>>>>>>>>>>>
response:Content-Type: application/json;charset=UTF-8
response:Transfer-Encoding: chunked
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: {"macAddress":"10.10.23.63","authorization_token":"authorization_token","userName":"lisi","userAge":"50"}
7.方法执行成功:okHttpPostQueryByByJson<<<<<<<<<<<
8.开始执行方法:okHttpSessionTest>>>>>>>>>>>
第一次未登录,则session相当于未空,所以无效
Set-Cookie: JSESSIONID=BFC0B4F8FA9FAC4BC35A5B356BF4000B;path=/;HttpOnly
Content-Type: text/plain;charset=UTF-8
Content-Length: 31
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: session为空,请重新登录
第二次登录,则session相当于有效
response:Content-Type: application/json;charset=UTF-8
response:Transfer-Encoding: chunked
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: {"passWord":"zhangsan@Pwd","userName":"zhagnsan"}
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: {"passWord":"zhangsan@Pwd","userName":"zhagnsan"}
8.方法执行成功:okHttpSessionTest<<<<<<<<<<<
9.开始执行方法:okHttpGetTest>>>>>>>>>>>
Content-Type: text/plain;charset=UTF-8
Content-Length: 11
Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: index/index
9.方法执行成功:okHttpGetTest<<<<<<<<<<<
10.开始执行方法:okHttpPostTest>>>>>>>>>>>
response:Content-Type: text/plain;charset=UTF-8
response:Content-Length: 11
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: index/index
10.方法执行成功:okHttpPostTest<<<<<<<<<<<
11.开始执行方法:okHttpFileUpLoad>>>>>>>>>>>
file is :D:\Users\source1\test.jpg
response:Content-Type: text/plain;charset=UTF-8
response:Content-Length: 124
response:Date: Thu, 21 Feb 2019 06:48:29 GMT
response content: 上传成功,上传之后文件的fileName为b57d05ef-d3cb-4e08-bc67-5964c2d514b2test.jpg文件路径为:D:\Users\target1\
11.方法执行成功:okHttpFileUpLoad<<<<<<<<<<<
Process finished with exit code 0
整体项目结构为
Pom.xml依赖为:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>httpStudy</groupId>
<artifactId>okHttp</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!--配置servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!--配置jsp jstl的支持-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!--对jsp的支持-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!-- End of Swagger -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.13.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
application.properties 配置为:
server.port=6080
server.tomcat.uri-encoding=utf-8
#视图层控制
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
#jsp不需要重启
server.jsp-servlet.init-parameters.development=true
三个包为:
cn.ok.http.main cn.ok.http.controller cn.ok.http.utils
依次创建文件如下:
WebMain.java
package cn.ok.http.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan({"cn.ok.http","springfox.*"})
public class WebMain {
public static void main(String[] args) throws Exception {
SpringApplication.run(WebMain.class, args);
}
}
WebMvcConfig.java
package cn.ok.http.main;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
// registry.addResourceHandler("/test/**").addResourceLocations("classpath:/test/image/"); //http://localhost:6080/test/1.png
// registry.addResourceHandler("/test/**").addResourceLocations("classpath:/test/"); //http://localhost:6080/test/image/1.png
super.addResourceHandlers(registry);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Swagger2.java
package cn.ok.http.main;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* 开启Swagger2
*
* @author Li Jian
*
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("cn.ok.http.controller")).paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("cn.ok.http.controller 集成系统API").build();
}
}
OkHttpController.java
package cn.ok.http.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import cn.ok.http.utils.FileUtil;
@RestController
@RequestMapping("/okHttp")
public class OkHttpController {
@RequestMapping(value = "/request", method = { RequestMethod.GET, RequestMethod.POST })
public String request() {
return "index/index";
}
@RequestMapping(value = "requestWithHeaders",method = { RequestMethod.GET, RequestMethod.POST } )
String requestWithHeaders(@RequestHeader(value = "authorization_token", required = true) String token,
@RequestHeader(value = "mac_address", required = true) String macAddress) {
return String.format("authorization_token is %s, mac_address is %s", token, macAddress);
}
@RequestMapping(value = "/requestWithParams",method = { RequestMethod.GET,RequestMethod.POST } )
String requestWithParams(@RequestParam(value = "userName" ,required = true) String paramNameUser,
@RequestParam(value = "userAge" ,required = true) int paramAge) {
return String.format("paramNameUser is %s, paramAge is %s", paramNameUser, paramAge);
}
@RequestMapping(value = "/requestWithHeadersAndParams",method = { RequestMethod.GET,RequestMethod.POST } )
String requestWithHeadersAndParams( @RequestParam(value = "userName" ,required = true) String paramNameUser,
@RequestParam(value = "userAge" ,required = true) int paramAge,
@RequestHeader(value = "authorization_token", required = true) String token,
@RequestHeader(value = "mac_address", required = true) String macAddress
) {
return String.format("paramNameUser is %s, paramAge is %s,authorization_token is %s,mac_address is %s", paramNameUser, paramAge,token,macAddress);
}
@RequestMapping(value = "/queryByByJson",method = { RequestMethod.POST } )
public Object queryByTipper(@RequestBody Map<String,String> request) {
return request;
}
@RequestMapping(value = "/sessionLogin", method = RequestMethod.POST)
public Object sessionLogin (String userName,String passWord ,HttpServletRequest request){
Map<String ,String> user = new HashMap<String, String>();
user.put("userName",userName);
user.put("passWord",passWord);
request.getSession().setAttribute("sessionUser" ,user);
return user;
}
@RequestMapping(value = "/sessionTimeOut", method = RequestMethod.GET)
public Object sessionTimeOut (HttpServletRequest request){
if(request.getSession().getAttribute("sessionUser") == null) {
return "session为空,请重新登录";
}
return request.getSession().getAttribute("sessionUser");
}
@RequestMapping(value="/uploadFile", method = RequestMethod.POST)
public String uploadImg(@RequestParam("file") MultipartFile file,
@RequestParam(value = "fileUpLoadPath", required = true) String fileUpLoadPath,
HttpServletRequest request,HttpServletRequest response) {
String contentType = file.getContentType(); //图片文件类型
String fileName = UUID.randomUUID() + file.getOriginalFilename(); //图片名字
if(file == null || StringUtils.isEmpty(file.getOriginalFilename())) {
return "上传文件不能为空";
}
Boolean fileEndWith =StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"jpg")
|| StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"png")
|| StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),"jpeg");
if(BooleanUtils.isFalse(fileEndWith)){
return "上传文件格式不对,格式必须是jpg,png,jpeg,JPG,PNG,JPEG中的一种";
}
//调用文件处理类FileUtil,处理文件,将文件写入指定位置
try {
FileUtil.uploadFile(file.getBytes(), fileUpLoadPath, fileName);
} catch (Exception e) {
return "上传文件失败,请重新上传,错误信息为 " + e ;
}
// 返回图片的存放路径
return "上传成功,上传之后文件的fileName为" + fileName +"文件路径为:" + fileUpLoadPath ;
}
}
FileUtil.java
package cn.ok.http.utils;
import java.io.File;
import java.io.FileOutputStream;
public class FileUtil {
//文件上传工具类服务方法
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception{
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
}
OKHttpUtils.java
package cn.ok.http.utils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
/**
* 参考地址: http://www.cnblogs.com/nihaorz/p/5334208.html
* mockserver https://blog.csdn.net/heymysweetheart/article/details/52227379
* <p>
* 依赖的OKHtttp3 依赖的 maven jar包,因为OKHttp没有依赖的cookie包,所以采用OKHTTP3包
* <dependency>
* <groupId>com.squareup.okhttp3</groupId>
* <artifactId>okhttp</artifactId>
* <version>3.13.1</version>
* </dependency>
* 处理json相关的jar包
* <dependency>
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>1.2.4</version>
* </dependency>
*/
public class OKHttpUtils {
private static OkHttpClient mOkHttpClient;
static {
httpClient();
}
public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException {
OKhttpTest.okHttpTest();
}
static OkHttpClient httpClient() {
mOkHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJar() {
//这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
return mOkHttpClient;
}
/**
* @param url 请求的url地址,如果还有params参数,则请求地址中必须是原始地址,不能再有参数
* @param header 请求的header参数,如果默认没有header参数,则设置为null即行
* @param params 请求的form表单参数,如果默认没有header参数,则设置为null即行
* @throws IOException
*/
static void httpGet(String url, Map<String, Object> header, Map<String, Object> params) throws IOException {
StringBuilder sb = new StringBuilder(url);
Request.Builder builder = new Request.Builder(); // .url(url);
Request request = null;
if (params != null) {
Boolean frist = true;
for (String key : params.keySet()) {
if (key != null && key.trim().length() > 0) {
if (url.contains("?")) {
throw new RuntimeException();
}
Object keyValue = params.get(key) == null ? "" : params.get(key);
sb.append(String.format("%s%s=%s", frist == true ? "?" : "&", key, keyValue));//构造get url 参数格式
frist = false;
}
}
}
builder.url(sb.toString());
if (header != null) {
for (String headerKey : header.keySet()) {
builder.addHeader(headerKey, header.get(headerKey).toString());
}
}
request = builder.build();
Response response = mOkHttpClient.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 content: " + response.body().string());
}
/**
* @param url
* @param json,如果json不存在,则传入为null
* @param requestType,必须传入
* @param header,请求头参数
* @throws IOException
*/
static void httpPost(String url, String json, Map<String, String> params, HTTP_CONTENT_TYPE requestType, Map<String, String> header) throws IOException {
if (requestType == null) {
throw new HttpException("请求类型必须传入不能为空", "400");
}
MediaType MEDIA_TYPE_TEXT = MediaType.parse(requestType.getContentType());
Request.Builder builder = new Request.Builder(); // .url(url);
Request request = null;
// json 请求
if (requestType.equals(HTTP_CONTENT_TYPE.APPLICATION_JSON)) {
if (json == null) {
json = "{}";
}
builder = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_TEXT, json));
}
// x-www-form-urlencoded 请求
if (requestType.equals(HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED)) {
FormBody.Builder formEncodingBuilder = new FormBody.Builder();
if (params != null) {
for (String key : params.keySet()) {
if (key != null && key.trim().length() > 0) {
String keyValue = params.get(key) == null ? "" : params.get(key);
formEncodingBuilder.add(key, keyValue);
}
}
}
RequestBody formBody = formEncodingBuilder.build();
builder = new Request.Builder()
.url(url)
.post(formBody);
}
if (header != null) {
for (String headerKey : header.keySet()) {
builder.addHeader(headerKey, header.get(headerKey).toString());
}
}
request = builder.build();
Response response = mOkHttpClient.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("response:" + responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println("response content: " + response.body().string());
}
/**
* @param url
* @param filePath
* @param fileName multipart/form-data 格式的请求,未进行封装
* @throws IOException
*/
static void httpPostFormDate(String url, String filePath, String fileName, String fileUpLoadPath) throws IOException {
String file = filePath + "\\" + fileName;
System.out.println("file is :" + file);
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpg");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"fileUpLoadPath\""), //指的是其他form表单的值的key
RequestBody.create(null, fileUpLoadPath)) //指的是其他form表单的值的value
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"" + fileName + "\""), //file指的是@RequestParam("file") MultipartFile file中的 file的名称,
RequestBody.create(MEDIA_TYPE_PNG, new File(file)))
.build();
Request request = new Request.Builder().url(url).post(requestBody).build(); // .url(url);
Response response = mOkHttpClient.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("response:" + responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println("response content: " + response.body().string());
}
}
enum HTTP_CONTENT_TYPE {
APPLICATION_X_WWW_FORM_URLENCODED("application/x-www-form-urlencoded;charset=utf-8"),
APPLICATION_JSON("application/json;charset=utf-8"),
MULTIPART_FORM_DATA("multipart/form-data");
private String contentType;
HTTP_CONTENT_TYPE(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return contentType;
}
}
class HttpException extends RuntimeException {
private String statusCode;
private String message;
public HttpException(String message, String statusCode) {
super(message);
this.statusCode = statusCode;
}
}
class OKhttpTest {
static void okHttpGetTest() throws IOException {
OKHttpUtils.httpGet("http://localhost:6080/okHttp/request", null, null);
}
static void okHttpPostTest() throws IOException {
OKHttpUtils.httpPost("http://localhost:6080/okHttp/request", null, null, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
}
static void okHttpGetWithParamsTest() throws IOException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "lisi");
params.put("userAge", 50);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithParams", null, params);
}
static void okHttpPostWithParamsTest() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithParams", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
}
static void okHttpGetTestWithHeads() throws IOException {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithHeaders", headers, null);
}
static void okHttpPostTestWithHeads() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithHeaders", null, null, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, headers);
}
static void okHttpGetTestWithHeadsParams() throws IOException {
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "lisi");
params.put("userAge", 50);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/requestWithHeadersAndParams", headers, params);
}
static void okHttpPostTestWithHeadsParams() throws IOException {
Map<String, String> headers = new HashMap<String, String>();
headers.put("authorization_token", "xysfafsxofweolxxepppp");
headers.put("mac_address", "10.10.23.63");
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/requestWithHeadersAndParams", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, headers);
}
static void okHttpPostQueryByByJson() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "lisi");
params.put("userAge", "50");
params.put("authorization_token", "authorization_token");
params.put("macAddress", "10.10.23.63");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/queryByByJson", JSON.toJSONString(params), params, HTTP_CONTENT_TYPE.APPLICATION_JSON, null);
}
static void okHttpSessionTest() throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("userName", "zhagnsan");
params.put("passWord", "zhangsan@Pwd");
System.out.println("第一次未登录,则session相当于未空,所以无效");
OKHttpUtils.httpGet("http://localhost:6080/okHttp/sessionTimeOut", null, null);
System.out.println("第二次登录,则session相当于有效");
OKHttpUtils.httpPost("http://localhost:6080/okHttp/sessionLogin", null, params, HTTP_CONTENT_TYPE.APPLICATION_X_WWW_FORM_URLENCODED, null);
OKHttpUtils.httpGet("http://localhost:6080/okHttp/sessionTimeOut", null, null);
}
static void okHttpFileUpLoad() throws IOException {
String filePath = "D:\\Users\\source1"; //源文件路径
String fileUpLoadPath = "D:\\Users\\target1\\"; //上传文件路径
String fileName = "test.jpg";
OKHttpUtils.httpPostFormDate("http://localhost:6080/okHttp/uploadFile", filePath, fileName, fileUpLoadPath);
}
static void okHttpTest() throws InvocationTargetException, IllegalAccessException {
Method[] methodArr = OKhttpTest.class.getDeclaredMethods();
System.out.println(String.format("test--->begin all 需要总共测试%s个方法", methodArr.length - 1));
int i = 1;
for (Method method : methodArr) {
if (method.getName().equals("okHttpTest")) {
continue;
}
System.out.println(i + "." + "开始执行方法:" + method.getName() + ">>>>>>>>>>>");
method.invoke(null, null);
System.out.println(i + "." + "方法执行成功:" + method.getName() + "<<<<<<<<<<<" + "\n\n\n");
i++;
}
}
}
csdn项目资源下载地址:https://download.csdn.net/download/qq_29956725/10968677
如果想要支持https,则需要绕过https校验,其代码为:
static OkHttpClient httpClient() {
OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
mBuilder.sslSocketFactory(createSSLSocketFactory());
mBuilder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
mOkHttpClient = mBuilder.cookieJar(new CookieJar() {
//这里一定一定一定是HashMap<String, List<Cookie>>,是String,不是url.
private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(), cookies);
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
return mOkHttpClient;
}
private static SSLSocketFactory createSSLSocketFactory() { SSLSocketFactory sSLSocketFactory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null,new TrustManager[]{new X509TrustManager(){ @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }},new SecureRandom()); sSLSocketFactory = sc.getSocketFactory(); } catch (Exception e) { } return sSLSocketFactory; }