public static JSONObject publishDmpCustomAudience() { String access_token = "xxx"; final Long advertiser_id = 0L; // 请求地址 String open_api_url_prefix = "https://ad.oceanengine.com/open_api/2/"; String uri = "dmp/custom_audience/publish/"; // 请求参数 Map data = new HashMap() { { put("advertiser_id", advertiser_id); put("custom_audience_id", 3); } }; // 构造请求 HttpPost httpEntity = new HttpPost(open_api_url_prefix + uri); httpEntity.setHeader("Access-Token", access_token); CloseableHttpResponse response = null; CloseableHttpClient client = null; try { client = HttpClientBuilder.create().build(); httpEntity.setURI(URI.create(open_api_url_prefix + uri)); httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON)); response = client.execute(httpEntity); if (response != null && response.getStatusLine().getStatusCode() == 200) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = bufferedReader.readLine()) != null) { result.append(line); } bufferedReader.close(); return JSONObject.parseObject(result.toString()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } client.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }这段代码能简写吗
时间: 2024-02-14 11:30:56 浏览: 22
可以简化这段代码。下面是简化后的代码:
```java
public static JSONObject publishDmpCustomAudience() {
String access_token = "xxx";
final Long advertiser_id = 0L;
// 请求地址
String open_api_url_prefix = "https://ad.oceanengine.com/open_api/2/";
String uri = "dmp/custom_audience/publish/";
// 请求参数
Map<String, Object> data = new HashMap<>();
data.put("advertiser_id", advertiser_id);
data.put("custom_audience_id", 3);
// 构造请求
HttpPost httpEntity = new HttpPost(open_api_url_prefix + uri);
httpEntity.setHeader("Access-Token", access_token);
httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON));
try (CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = client.execute(httpEntity)) {
if (response != null && response.getStatusLine().getStatusCode() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
bufferedReader.close();
return JSONObject.parseObject(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
```
这里的改动包括:
- 使用泛型指定 `data` 的类型为 `Map<String, Object>`;
- 使用 try-with-resources 简化关闭资源的代码;
- 使用 `StringBuilder` 替代 `StringBuffer`,因为前者是线程安全的,后者不是;
- 移除了无用的异常捕获。
这样代码会更简洁和易读。