java发送http请求有很多种方式和写法,下面这种方式是使用java原生代码的实现,以url传递参数的方式
public JSONObject invoke(Map<String, Object> params) {
try {
apiUrl = propertyPlaceUtil.getTdApiUrl();
String urlString = new StringBuilder().append(apiUrl).toString();
URL url = new URL(urlString);
// 组织请求参数
StringBuilder postBody = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() == null) continue;
postBody.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(),"utf-8")).append("&");
}
if (!params.isEmpty()) {
postBody.deleteCharAt(postBody.length() - 1);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setConnectTimeout(1000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(postBody.toString().getBytes("UTF-8"));
conn.getOutputStream().flush();
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
logger.warn("invoke failed, response status:" + responseCode);
return null;
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
return JSON.parseObject(result.toString().trim());
} catch (Exception e) {
logger.error("invoke throw exception, details: " + e);
}
return null;
}