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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | package com.honghu.cloud.tools; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSON; import com.google.common.collect.Maps; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.Headers; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; @Component public class OkHttpUtil implements InitializingBean { private static int DEFAULT_READ_TIMEOUT_MILLIS = 500; private static int DEFAULT_CONNECT_TIMEOUT_MILLIS = 500; private static int DEFAULT_WRITE_TIMEOUT_MILLIS = 500; public static final MediaType JSONTYPE = MediaType.parse("application/json; charset=utf-8"); private OkHttpClient client; /** * get请求 * * @param url * @return */ public static String httpGet(String url) { String result = null; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); try { Response response = client.newCall(request).execute(); result = response.body().string(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * 处理get请求,兼容原httpClient请求 * @param baseUrl * @param url * @param nvp * @param headers * @param cookies * @return * @throws Exception */ public Map<String , Object> doGet(String baseUrl, String url, List<NameValuePair> nvp, List<Header> headers) throws Exception { //Request build对象,get请求没有method方法,默认是PUT方式请求,直接在URL做参数处理 Request.Builder builder = getBuilder(baseUrl, url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(nvp, "UTF-8"))); builder.get(); //处理headers doHeaders(headers, builder); //创建Request Request request = builder.build(); //同步请求并获取Response Response response = client.newCall(request).execute(); //校验并返回 Map<String, Object> maps = Maps.newHashMap(); if (response.isSuccessful()) { maps.put("code", 200); maps.put("data", response.body().string()); return maps; } else { maps.put("code", 500); maps.put("data", response.body().string()); return maps; } } /** * 处理post请求,兼容原httpClient请求 * @param baseUrl * @param url * @param nvp * @param headers * @return * @throws Exception */ public Map<String , Object> doPost(String baseUrl, String url, List<NameValuePair> nvp , String type , Header... headers) throws Exception { //Request build对象 Request.Builder builder = getBuilder(baseUrl, url); //处理headers doHeaders(builder, headers); //处理请求参数 doPostRequestBody(builder, nvp,type); //创建Request Request request = builder.build(); //同步请求并获取Response Response response = client.newCall(request).execute(); //校验并返回 Map<String, Object> maps = Maps.newHashMap(); if (response.isSuccessful()) { maps.put("code", 200); maps.put("data", response.body().string()); return maps; } else { maps.put("code", 500); maps.put("message", response.body().string()); return maps; } } /** * post请求参数写入Request.Builder * @param builder * @param nvp */ private void doPostRequestBody(Request.Builder builder, List<NameValuePair> nvp,String type) { RequestBody body =null; if("json".equals(type)){ Map<String, Object> maps = Maps.newHashMap(); for (NameValuePair bean : nvp) { maps.put(bean.getName(), bean.getValue()); } body = RequestBody.create(JSONTYPE, JSON.toJSONString(maps)); builder.post(body); }else if("form".equals(type)){ FormEncodingBuilder form = new FormEncodingBuilder(); if (!CollectionUtils.isEmpty(nvp)) { for (NameValuePair bean : nvp) { form.add(bean.getName(), bean.getValue()); } body= form.build(); } } builder.post(body); } /** * 获取Request.Builder * @param baseUrl * @param url * @return */ private Request.Builder getBuilder(String baseUrl, String url) { return new Request.Builder().url(String.format("%s%s", baseUrl, url)); } /** * 处理请求headers * @param headers * @param builder */ private void doHeaders(List<Header> headers, Request.Builder builder) { if (!CollectionUtils.isEmpty(headers)) { Headers.Builder headeBuilder = new Headers.Builder(); for (Header header : headers) { headeBuilder.add(header.getName(), header.getValue()); } builder.headers(headeBuilder.build()); } } /** * 处理请求headers * @param headers * @param builder */ private void doHeaders(Request.Builder builder, Header[] headers) { if (headers != null && headers.length > 0) { Headers.Builder headeBuilder = new Headers.Builder(); for (Header header : headers) { headeBuilder.add(header.getName(), header.getValue()); } builder.headers(headeBuilder.build()); } } @Override public void afterPropertiesSet() throws Exception { client = new OkHttpClient(); client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } } |
pom 文件
com.squareup.okhttp
okhttp
2.7.5