use okhttp for http request

This commit is contained in:
heavyrain.lee
2019-04-27 10:43:04 +08:00
parent 744d516932
commit 928555b36e
2 changed files with 30 additions and 53 deletions
+9
View File
@@ -249,6 +249,15 @@
<version>1.4.197</version> <version>1.4.197</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.13.1</version>
</dependency>
</dependencies> </dependencies>
@@ -9,6 +9,7 @@
package win.liyufan.im; package win.liyufan.im;
import io.netty.util.internal.StringUtil; import io.netty.util.internal.StringUtil;
import okhttp3.*;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
@@ -20,73 +21,40 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
public class HttpUtils { public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class); private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
static private OkHttpClient client = new OkHttpClient();
public static boolean httpJsonPost(String url, String jsonStr){ public static void httpJsonPost(final String url, final String jsonStr){
boolean isSuccess = false;
LOG.info("POST to {} with data {}", url, jsonStr); LOG.info("POST to {} with data {}", url, jsonStr);
if (StringUtil.isNullOrEmpty(url)) { if (StringUtil.isNullOrEmpty(url)) {
LOG.error("http post failure with empty url"); LOG.error("http post failure with empty url");
return false; return;
} }
HttpPost post = null; RequestBody body = RequestBody.create(JSON, jsonStr);
try { Request request = new Request.Builder()
HttpClient httpClient = HttpClientBuilder.create().build(); .url(url)
// // 设置超时时间 .post(body)
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); .build();
// httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000); client.newCall(request).enqueue(new Callback() {
@Override
post = new HttpPost(url); public void onFailure(Call call, IOException e) {
// 构造消息头 e.printStackTrace();
post.setHeader("Content-type", "application/json; charset=utf-8"); LOG.info("POST to {} with data {} failure", url, jsonStr);
post.setHeader("Connection", "Keep-Alive");
// 构建消息实体
StringEntity entity = new StringEntity(jsonStr, Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
// 检验返回码
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
LOG.info("请求出错: "+statusCode);
isSuccess = false;
}else{
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String content = sb.toString();
LOG.info("http request response content: {}", content);
} }
} catch (Exception e) {
e.printStackTrace(); @Override
Utility.printExecption(LOG, e); public void onResponse(Call call, Response response) throws IOException {
isSuccess = false; LOG.info("POST to {} success with response", url, response.body().string());
}finally{
if(post != null){
post.releaseConnection();
} }
} });
return isSuccess;
} }
} }