舉個列子
使用java如何實現以下請求curl -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{
"grant_type": "client_credentials",
"client_id": "YXA6i-Ak8Ol4Eei2l11ZjV-EAg",
"client_secret": "YXA6VunqiNxoB7IwXHInk1cGiXOOJfc",
"ttl": "1024000"
}' 'http://a1.easemob.com/easemob-demo/testapp/token'
可以使用Java中的HttpURLConnection或者Apache HttpClient來實現此curl請求,以下是使用HttpURLConnection的範例程式碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Example {
public static void main(String[] args) throws IOException {
URL url = new URL("http://a1.easemob.com/easemob-demo/testapp/token");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
String jsonBody = "{\"grant_type\":\"client_credentials\",\"client_id\":\"YXA6i-Ak8Ol4Eei2l11ZjV-EAg\",\"client_secret\":\"YXA6VunqiNxoB7IwXHInk1cGiXOOJfc\",\"ttl\":\"1024000\"}";
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(jsonBody.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
除了使用HttpURLConnection或者Apache HttpClient,還可以使用一些第三方開發庫進行訪問。
例如,可以使用OkHttp,以下是使用OkHttp的範例程式碼:
import okhttp3.*;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"grant_type\":\"client_credentials\",\"client_id\":\"YXA6i-Ak8Ol4Eei2l11ZjV-EAg\",\"client_secret\":\"YXA6VunqiNxoB7IwXHInk1cGiXOOJfc\",\"ttl\":\"1024000\"}");
Request request = new Request.Builder()
.url("http://a1.easemob.com/easemob-demo/testapp/token")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
此外,如果使用Spring Framework或Spring Boot ,可以使用Spring的RestTemplate或WebClient訪問API。處理HTTP請求更簡單易用。
以下是使用RestTemplate的範例程式碼:
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class Example {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Accept", "application/json");
String jsonBody = "{\"grant_type\":\"client_credentials\",\"client_id\":\"YXA6i-Ak8Ol4Eei2l11ZjV-EAg\",\"client_secret\":\"YXA6VunqiNxoB7IwXHInk1cGiXOOJfc\",\"ttl\":\"1024000\"}";
ResponseEntity<String> response = restTemplate.postForEntity("http://a1.easemob.com/easemob-demo/testapp/token", headers, jsonBody, String.class);
System.out.println(response.getBody());
}
}
或者使用hutool-all工具類中的HttpResponse訪問API。
使用的依賴是
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.18version>
dependency>
final String targetUrl = ”http://a1.easemob.com/easemob-demo/testapp/token“;
final Map<String, Object> params = new HashMap<>();
params.put("grant_type", "client_credentials");
params.put("client_id", this.huaXinConfig.getClientId());
params.put("client_secret", this.huaXinConfig.getClientSecret());
HttpResponse response = HttpRequest.post(targetUrl).body(JSONUtil.toJsonStr(params)).timeout(20000).execute();
if (!response.isOk()) {
return null;
}
String jsonBody = response.body();