【问题标题】:Proper way to format a JSON object and send to server via volley格式化 JSON 对象并通过 volley 发送到服务器的正确方法
【发布时间】:2018-06-01 00:50:30
【问题描述】:

我正在尝试使用来自 google 的 Safe Browsing 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 和连接错误,我做错了什么?

【问题讨论】:

  • 这看起来完全错误。 square brackets 表示它是一个数组。我建议您实际创建 Java 类以映射到此。从 client 开始,它有一个 clientId 和一个 clientVersion 和一个 threatInfo 类,它有一个字符串数组等,然后使用 Jackson 将这些对象序列化为 JSON
  • 如果您使用的是 Android,请查看 developer.android.com/training/safetynet/safebrowsing
  • @Shmuel 我在 android 的安全浏览库之前尝试过,但我无法在我的项目中使用它,总是将坏链接作为安全链接抛出

标签: java android json android-volley


【解决方案1】:

您应该使用 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);

【讨论】:

  • 你成功了!它的格式很好,但有一个更正:JSONArray platformTypes = new JSONArray(); platformTypes.put("WINDOWS"); JSONArray threatEntryTypes = new JSONArray(); threatEntryTypes.put("URL"); 奇怪的是,文档引用 JSONArray put 方法只表明您实际上可以放置 int, long, double, objectboolean 但不是 字符串
猜你喜欢
  • 1970-01-01
  • 2014-11-06
  • 2016-01-30
  • 1970-01-01
  • 2011-03-11
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
相关资源
最近更新 更多