web services 请求get 和post方式

/**
* 发送请求get方式请求
*/
public static String doConnectGet(String input, String url) throws SchedulerException, IOException {
StringBuffer resultBuffer = null;
// 构建请求参数
// StringBuffer sbParams = new StringBuffer();
// if (params != null && params.size() > 0) {
// for (Entry<String, Object> entry : params.entrySet()) {
// sbParams.append(entry.getKey());
// sbParams.append("=");
// sbParams.append(entry.getValue());
// sbParams.append("&");
// }
// }
HttpURLConnection con = null;
BufferedReader br = null;
try {
URL urlGet = new URL(url);
// if (sbParams != null && sbParams.length() > 0) {
// url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
// } else {
// url = new URL(urlParam);
// }
con = (HttpURLConnection) urlGet.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException("连接失败!");
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
return resultBuffer.toString();
}



/**
* 发送请求post方式
*/
public static String doConnect(String input, String url) throws SchedulerException, IOException {
String result = null;
try {
URL urlPost = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlPost.openConnection();
http.setRequestMethod("POST");

http.setDoOutput(true);
http.setDoInput(true);
http.setRequestProperty("content-Type", "application/json");
http.setRequestProperty("charset", "utf-8");
// http.setRequestProperty("Authorization", authStr); //如果需要登录的时候,添加该参数
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

http.connect();
OutputStream os = http.getOutputStream();
if (StringUtil.isNotEmpty(input)) {
os.write(input.getBytes("UTF-8"));// 传入参数
}
InputStream is = http.getInputStream();
//原始版本http请求数据获取数据流大小,可能导致数据流分段返回,通过available()方法获取不到文件流总大小
// int size = is.available();
// byte[] jsonBytes = new byte[size];
// is.read(jsonBytes);
// result = new String(jsonBytes, "UTF-8");

//修改后的版本
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String tempbf;
StringBuffer html = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
html.append(tempbf);
}
result = html.toString();
os.flush();
os.close();
http.disconnect();
} catch (Exception e) {
throw new RuntimeException("连接失败!");
}

return result;
}
原文地址:https://www.cnblogs.com/wcnwcn/p/8548027.html