分三步:
1:申请 账号,密码
2:得到token
3:使用token,调用api
2 得到token
public String getToken() {
String token = "";
String authorization = new BASE64Encoder().encode((consumerKey + ":" + consumerSecret).getBytes());
authorization = authorization.trim();
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodingBuilder().add("grant_type", "client_credentials").build();
Request request = new Request.Builder().url(tokenUrl).post(formBody)
.addHeader("authorization", "Basic " + authorization)
.addHeader("content-type", "application/x-www-form-urlencoded").addHeader("cache-control", "no-cache")
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
JSONObject ret = JSONObject.parseObject(result);
token = ret.getString("access_token");
return token;
}
} catch (IOException e) {
e.printStackTrace();
}
return token;
}
3. 使用token 调用api
public String testOSP(String param) {
String result = "";
String token = wso2Uitil.getToken();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), param);
Request request = new Request.Builder().url(ospurl).post(body)
.addHeader("authorization", "Bearer " + token)
.addHeader("cache-control", "no-cache").build();
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}