import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
public class HttpClientUtil {
public static String doPost(String path, String body) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//发送 POST 请求必须设置为 true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(120000);
conn.setReadTimeout(120000);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
//获取输出流
out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
String jsonStr = body;
String encoding = out.getEncoding();
out.write(jsonStr);
out.flush();
out.close();
//取得输入流,并使用 Reader 读取
if (200 == conn.getResponseCode()) {
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
System.out.println(line);
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return result.toString();
}
public static String doGet(String path, Map<String, Object> params) {
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try {
if (params != null) {
String paramStr = "";
for (String key : params.keySet()) {
if (!paramStr.isEmpty()) {
paramStr += '&';
}
paramStr += key + '=' + params.get(key).toString();
}
if (path.indexOf('?') > 0) {
path += '&' + paramStr;
} else {
path += '?' + paramStr;
}
}
//创建远程 url 连接对象
URL url = new URL(path);
//通过远程 url 连接对象打开一个连接,强转成 HTTPURLConnection 类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(120000);
conn.setReadTimeout(120000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
conn.connect();
//通过 conn 取得输入流,并使用 Reader 读取
if (200 == conn.getResponseCode()) {
is = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null) {
result.append(line);
System.out.println(line);
}
} else {
System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
}
} catch (MalformedURLException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
conn.disconnect();
}
return result.toString();
}
}
|