首页 > 解决方案 > 格式化 JSON 对象并通过 volley 发送到服务器的正确方法

问题描述

我正在尝试使用谷歌的安全浏览 API来检查网络链接是否被列入黑名单,只需将 JSON 对象中的请求发送到:

POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY HTTP/1.1
Content-Type: application/json

JSON 对象应该是这样的:

{
 "client": {
   "clientId":      "mycompanyname",
   "clientVersion": "1.1"
 },
 "threatInfo": {
   "threatTypes":      ["MALWARE", "SOCIAL_ENGINEERING"],
   "platformTypes":    ["WINDOWS"],
   "threatEntryTypes": ["URL"],
   "threatEntries": [
     {"url": "http://www.urltocheck1.org/"},
     {"url": "http://www.urltocheck2.org/"},
     {"url": "http://www.urltocheck3.com/"}
   ]
 }
}

但是我已经不知道我是否正确格式化了我的 JSON 对象,或者我的代码是否正确,见下文:

public class SB {
  private ArrayList<String> url; //URL's a analizar
  private String key; //API key
  private RequestQueue queue;
  private Context context;
  private ArrayList<SBthreat> AnalyzedUrl; //analysis final
  private boolean Interrupted = false;
  private boolean CallFail = false;

  public SB(Context context, ArrayList<String> url, String key){
      this.url = url;
      this.key = key;
      this.context = context;
      queue = Volley.newRequestQueue(context);

      AnalyzedUrl = new ArrayList<>();
  }

  public void Request(){
      final StringBuilder api = new StringBuilder("https://safebrowsing.googleapis.com/v4/threatMatches:find?key=");
      JSONObject requestBody = new JSONObject();

      //JSON body
      try {
          JSONObject client = new JSONObject();
          client.put("clientId", "NetworkSentinel");
          client.put("clientVersion", "1.2");

          JSONObject threatEntries = new JSONObject();

          for(int i = 0; i < this.url.size(); i++){
              threatEntries.put("url", this.url.get(i)); //-----> the url can be too many
          }

          JSONObject threatInfo = new JSONObject();
          threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]");
          threatInfo.put("platformTypes", "[\"WINDOWS\"]");
          threatInfo.put("threatEntryTypes", "[\"URL\"]");
          threatInfo.put("threatEntries", threatEntries);

          JSONObject jsonBody = new JSONObject();
          jsonBody.put("client", client);
          jsonBody.put("threatInfo", threatInfo);

          requestBody.put("", jsonBody);

      }catch (JSONException e) {
          e.printStackTrace();
      }

      api.append(key).append(" HTTP/1.1");

      Log.i("SB", api.toString().replace(key, "XXXXXXXXXXXXX"));

      RequestFuture<JSONObject> future = RequestFuture.newFuture();

      JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, api.toString(), requestBody, future, future){
          @Override
          public HashMap<String, String> getHeaders() {
              HashMap<String, String> params = new HashMap<>();
              params.put("Content-Type", "application/json");
              return params;
          }
      };

      queue.add(request);

      try {
          JSONObject response = future.get();
          if(response.length() != 0) {

              Log.i("SB", "-----------------------------------------------------------------------");
              Log.i("response", response.toString());

              Interrupted = false;
              CallFail = false;
          }
      } catch (InterruptedException e) {
          e.printStackTrace();
          Interrupted = true;
      } catch (ExecutionException e) {
          e.printStackTrace();
          CallFail = true;
      }
  }

  public ArrayList<SBthreat> GetAnalysis(){
      return AnalyzedUrl;
  }

  public boolean isInterrupted(){
      return Interrupted;
  }

  public boolean isCallFail(){
      return CallFail;
  }
}

代码threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]");写得好吗?或者有没有更好的方法将数据放在方括号中?

当我运行我的代码时,总是会出现错误com.android.volley.ClientError和连接错误,我做错了什么?

标签: javaandroidjsonandroid-volley

解决方案


您应该使用 JSONArray 而不要使用[ ]手动放置。请参考以下:

    JSONObject client = new JSONObject();
    client.put("clientId", "mycompanyname");
    client.put("clientVersion", "1.1");

    JSONObject threatInfo = new JSONObject();
    JSONArray threatTypes = new JSONArray();
    threatTypes.put("MALWARE");
    threatTypes.put("SOCIAL_ENGINEERING");

    JSONArray platformTypes = new JSONArray();
    threatTypes.put("WINDOWS");

    JSONArray threatEntryTypes = new JSONArray();
    threatTypes.put("URL");

    JSONArray threatEntries = new JSONArray();
    for(int i = 0; i < this.url.size(); i++){
        JSONObject threatEntry = new JSONObject();
        threatEntry.put("url", this.url.get(i)); //-----> the url can be too many
        threatEntries.put(threatEntry);
    }

    threatInfo.put("threatTypes", threatTypes);
    threatInfo.put("platformTypes", platformTypes);
    threatInfo.put("threatEntryTypes", threatEntryTypes);
    threatInfo.put("threatEntries", threatEntries);

推荐阅读