java发送http请求

    技术2022-07-13  73

    代码例子: String url = "xxxxx"; CloseableHttpClient httpClient = HttpClients.createDefault(); // httpclient HttpPost httpPost = new HttpPost(url); // 创建httpPost对象,传入url // 在post中增加请求头 httpPost.addHeader("Authorization", "xxxxxxxxx"); httpPost.addHeader("Content-Type", "application/json"); // 在post中添加请求体 JSONObject params = new JSONObject(); params.put("cname", AccessChannel); params.put("uid", RecordingUID); params.put("clientRequest", new JSONObject()); httpPost.setEntity(new StringEntity(params.toJSONString()));// 加入到请求体中。 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); // 获取响应。 HttpEntity entity = httpResponse.getEntity(); // 获取响应体。 String result = EntityUtils.toString(entity, CharsetUtils.get(UTF_8));// 将响应体转成字符串。 JSONObject jsonObject = JSONObject.parseObject(result); // 将响应体转成jsonObject return (String) jsonObject.get("resourceId"); 为了简化,可以写一个类:ImHttpClient单例模式懒加载(http连接池)然后传入请求头的Map,请求体的Map,和url,和timeout时间等等。这样就很简洁。 String url = "xxxxxx"; // 请求头 Map<String, Object> headers = new HashMap<>(); headers.put("Authorization", "xxxx"); // 请求体 JSONObject params = new JSONObject(); params.put("cname", xxx); params.put("uid", xxxx); params.put("clientRequest", new JSONObject()); String result = null; try { // 获取请求结果 result = ImHttpClient.getHttpClient().postJSONSend(headers, params, url); JSONObject jsonObject = JSONObject.parseObject(result); // 将响应体转成jsonObject return (String) jsonObject.get("resourceId"); } catch (Exception e) { log.error("agoraAcquire error {}", ExceptionUtils.getStackTrace(e)); } finally { log.info("agoraAcquire accessChannel:{} recordingUID:{} url:{} result:{}", accessChannel, recordingUID, url, result); } return null;
    Processed: 0.011, SQL: 9