使用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'
时间: 2023-06-07 21:07:54 浏览: 200
使用Java可以通过HttpURLConnection或者OkHttp库发送POST请求实现以下命令:
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'
示例代码:
使用HttpURLConnection发送POST请求:
```java
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPost {
public static void main(String[] args) throws Exception{
String url = "http://a1.easemob.com/easemob-demo/testapp/token";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//添加请求头
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
//发送POST请求
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes("{ \"grant_type\": \"client_credentials\", \"client_id\": \"YXA6i-Ak8Ol4Eei2l11ZjV-EAg\",\"client_secret\": \"YXA6VunqiNxoB7IwXHInk1cGiXOOJfc\",\"ttl\": \"1024000\" }");
wr.flush();
wr.close();
//读取响应
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印响应结果
System.out.println(response.toString());
}
}
```
使用OkHttp库发送POST请求:
```java
import okhttp3.*;
import java.io.IOException;
public class OkHttpPost {
public static void main(String[] args) throws Exception{
String url = "http://a1.easemob.com/easemob-demo/testapp/token";
String json = "{ \"grant_type\": \"client_credentials\", \"client_id\": \"YXA6i-Ak8Ol4Eei2l11ZjV-EAg\",\"client_secret\": \"YXA6VunqiNxoB7IwXHInk1cGiXOOJfc\",\"ttl\": \"1024000\" }";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
//发送POST请求
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
```
阅读全文