Android定制化图像接口示例代码
~肾虚道长~ 发布于2018-08 浏览:1177 回复:1
1
收藏

参考百度AI-SDK :https://github.com/Baidu-AIP/java-sdk

将网络模块换成了OKHTTP  ,JSON 用的 fastjson

注意OKHTTP:如果Mediatype 不是用的json 会自动被urlencode

 

 public JSONObject basicMeterFramUrl( HashMap options) {

    //将参数转为一个json
    JSONObject   jsonObject = new JSONObject();
    if(null != options){
      for (String s : options.keySet()) {
        jsonObject.put(s,options.get(s));
      }
    }
    RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
        , jsonObject.toJSONString());
    Request   request  = new Request.Builder().url(METER_FRAM_API_HOST)
        .build();

   //获取token
   request = preOperation(request);

  
    //组装路径,必须在url 中带token
    String   newUrl = request.url().toString();
    if(!newUrl.endsWith("?")){
      newUrl = newUrl+"?";
    }
    newUrl= newUrl+"access_token="+accessToken+"&aipSdk=java";

    //复制一个request ,修改地址
    request = request.newBuilder().url(newUrl)
        .post(requestBody).build();

    //post参数处理,这里目前没有用到 
    request =postOperation(request);

    //发请求
    return requestServer(request);
  }

 

protected JSONObject requestServer(Request request) {
    // 请求API
    HttpLoggingInterceptor   loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient   okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
    String resData = null;
    Response  response =null;
    try {
      response =okHttpClient.newCall(request).execute();
      resData = response.body().string();
      Integer status = response.code();
      if (status.equals(200) && !resData.equals("")) {
        try {
          JSONObject res = JSON.parseObject(resData);
          if (state.getState().equals(EAuthState.STATE_POSSIBLE_CLOUD_USER)) {
            boolean cloudAuthState = res.containsKey("error_code")
                || res.getIntValue("error_code") != AipClientConst.IAM_ERROR_CODE;
            state.transfer(cloudAuthState);

            if (!cloudAuthState) {
              return Util.getGeneralError(
                  AipClientConst.OPENAPI_NO_ACCESS_ERROR_CODE,
                  AipClientConst.OPENAPI_NO_ACCESS_ERROR_MSG);
            }
          }
          return res;
        } catch (JSONException e) {
          return Util.getGeneralError(-1, resData);
        }
      }
      else {
        Log.w("Api",String.format("call failed! response status: %d, data: %s", status, resData));
        return AipError.NET_TIMEOUT_ERROR.toJsonResult();

      }
    } catch (IOException e) {
      e.printStackTrace();
      return  Util.getGeneralError(-1,e.getMessage());
    }

  }
//获取token  必须get 请求
public static JSONObject oauth(String apiKey, String secretKey, AipClientConfiguration config) {
    try {
      HttpLoggingInterceptor   loggingInterceptor = new HttpLoggingInterceptor();
      loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
      OkHttpClient   okHttpClient = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
      String getAccessTokenUrl = AipClientConst.OAUTH_URL
          // 1. grant_type为固定参数
          + "?grant_type=client_credentials"
          // 2. 官网获取的 API Key
          + "&client_id=" + apiKey
          // 3. 官网获取的 Secret Key
          + "&client_secret=" + secretKey;
      System.out.println("url="+getAccessTokenUrl);
      //RequestBody  requestBody = new FormBody.Builder()
      //    .add("grant_type","client_credentials")
      //    .add("client_id",apiKey)
      //    .add("client_secret",secretKey).build();
      Request   request = new Request.Builder().url(getAccessTokenUrl).get().build();
      Response  response = okHttpClient.newCall(request).execute();
      if(response.isSuccessful()){
        String   result = response.body().string();
         return JSON.parseObject(result);
      }else{
        return Util.getGeneralError(response.code(), "Server response code: " + response.code());
      }

    }  catch (IOException e) {
      e.printStackTrace();
    }
    return Util.getGeneralError(-1, "unknown error");
  }
收藏
点赞
1
个赞
共1条回复 最后由方舟舟若干号回复于2018-08
#2方舟舟若干号回复于2018-08

鼓掌

0
TOP
切换版块