/**
* 向server端发送请求,并获取返回参数
*
* @param actionUrl
* @param method
* @param param
* @return
*/
public static String sendPostRequest(String serverUrl, String param) {
logger.debug("+++++++++++++++sendPostRequest方法开始!+++++++++++++++++++");
StringBuffer sb = new StringBuffer();
String output = "";
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Charset", "utf-8");
conn.setRequestProperty("Content-Type", "application/json");
//解决乱码代码
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
if (param != null) {
OutputStream os = conn.getOutputStream();
os.write(param.getBytes("utf-8"));
os.flush();
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(sb);
}
/**
* 向server端发送请求,并获取返回参数
*
* @param actionUrl
* @param method
* @param param
* @return
* @throws UnsupportedEncodingException
*/
public static String sendGetRequest(String targetURL) throws UnsupportedEncodingException{
logger.debug("+++++++++++++++sendGetRequest方法开始!+++++++++++++++++++");
String output = "";
String outStr = "";
try {
URL restServiceURL = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Charset", "utf-8");
httpConnection.setRequestProperty("Content-Type", "application/json");
//解决乱码代码
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
httpConnection.setRequestProperty("Accept-Encoding", "utf-8");
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(), "utf-8"));
while ((output = responseBuffer.readLine()) != null) {
outStr = outStr + output;
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
logger.error("io Exception:see code");
e.printStackTrace();
}
return outStr;
}
调取第三方接口的post及get方法
最新推荐文章于 2024-05-16 17:36:27 发布