1.Post方法工具类
public static String verifyBossData(String data){
if(StringUtils.isBlank(data)){
return null;
}
//获取配置文件中url
String url = MongoDBUtil.getSystemParamKeyValue("bossServerUrl");
String result = null;
if(StringUtils.isNotBlank(data)){
BufferedReader reader = null;
HttpURLConnection conn = null;
OutputStreamWriter out = null;
StringBuffer strBuf = null;
try {
URL myUrl = new URL(url);
conn = (HttpURLConnection) myUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);//POST请求不能使用缓存
conn.setRequestProperty("charset", "UTF-8");
strBuf = new StringBuffer();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
out.write(data);
// flush输出流的缓冲
out.flush();
//读取URL的响应
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line =null;
while ((line = reader.readLine()) != null) {
strBuf.append(line);
}
result = strBuf.toString();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
2.Get方法工具类
注意:若data中包含空格,需要特殊处理
data = URLEncoder.encode(data, "UTF-8");
public static String sendGet(String data){
if(StringUtils.isBlank(data)){
return null;
}
//获取配置文件中url
String url = MongoDBUtil.getSystemParamKeyValue("bossServerUrl");
String result = null;
if(StringUtils.isNotBlank(data)){
//拼接URL
url += "?"+data;
BufferedReader reader = null;
HttpURLConnection conn = null;
OutputStreamWriter out = null;
StringBuffer strBuf = null;
try {
URL myUrl = new URL(url);
conn = (HttpURLConnection) myUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("Get");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("charset", "UTF-8");
strBuf = new StringBuffer();
//读取URL的响应
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line =null;
while ((line = reader.readLine()) != null) {
strBuf.append(line);
}
result = strBuf.toString();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(out!=null){
out.close();
}
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}