Files
IM-server-new/broker/src/main/java/win/liyufan/im/HttpUtils.java
T

61 lines
2.0 KiB
Java
Raw Normal View History

2019-03-16 17:04:23 +08:00
/*
* This file is part of the Wildfire Chat package.
* (c) Heavyrain2012 <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package win.liyufan.im;
import io.netty.util.internal.StringUtil;
2019-04-27 10:43:04 +08:00
import okhttp3.*;
2019-03-16 17:04:23 +08:00
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
2019-04-27 10:43:04 +08:00
import java.io.IOException;
2019-03-16 17:04:23 +08:00
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class HttpUtils {
private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
2019-04-27 10:43:04 +08:00
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
static private OkHttpClient client = new OkHttpClient();
2019-03-16 17:04:23 +08:00
2019-04-27 10:43:04 +08:00
public static void httpJsonPost(final String url, final String jsonStr){
2019-03-16 17:04:23 +08:00
LOG.info("POST to {} with data {}", url, jsonStr);
if (StringUtil.isNullOrEmpty(url)) {
LOG.error("http post failure with empty url");
2019-04-27 10:43:04 +08:00
return;
2019-03-16 17:04:23 +08:00
}
2019-04-27 10:43:04 +08:00
RequestBody body = RequestBody.create(JSON, jsonStr);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
LOG.info("POST to {} with data {} failure", url, jsonStr);
2019-03-16 17:04:23 +08:00
}
2019-04-27 10:43:04 +08:00
@Override
public void onResponse(Call call, Response response) throws IOException {
LOG.info("POST to {} success with response", url, response.body().string());
2019-03-16 17:04:23 +08:00
}
2019-04-27 10:43:04 +08:00
});
2019-03-16 17:04:23 +08:00
}
}