package utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public static JSONObject get(String url){
HttpURLConnection http = null;
InputStream is = null;
try {
URL urlGet = new URL(url);
http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
is =http.getInputStream();
int size =is.available();
byte[] jsonBytes =new byte[size];
is.read(jsonBytes);
String message=new String(jsonBytes,"UTF-8");
return JSONObject.parseObject(message);
} catch (Exception e) {
return null;
}finally {
if(null != http) http.disconnect();
try {
if (null != is) is.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
public static JSONObject doPost(String url, String params) throws Exception {
Request request = Request.Post(url);
if (params != null)
request.bodyByteArray(params.getBytes("UTF8"));
Response response = request.execute();
String jsonData = response.returnContent().asString();
JSONObject json = JSONObject.parseObject(jsonData);
return json;
}
public static JSONObject doGet(String url) throws Exception{
Request request = Request.Get(url);
request.setHeader("Content-type", "application/json;charset=UTF8");
Response response = request.execute();
String jsonData = response.returnContent().asString();
JSONObject json = JSONObject.parseObject(jsonData);
return json;
}
}