所以我请求一个API调用来按电话号码搜索记录。如果响应不成功,我想更改URL以按名称搜索记录。为了发送请求并获得响应,我们有一个try-catch子句。我唯一的想法是使用原始catch子句中的新URL重复请求和响应。有人能告诉我,如果原始请求遇到异常,我应该如何更改URL并发出新请求吗。这是我请求按电话号码搜索的代码片段。以及由于请求失败而显而易见的堆栈跟踪。
OkHttpClient client = new OkHttpClient().newBuilder().build();
String phone = DNC_List[i].getNumber();
Request request = new Request.Builder().url("https://www.zohoapis.com/crm/v2/Leads/search?phone=" + phone)
.method("GET", null).addHeader("Authorization", "Zoho-oauthtoken 1000.xxxxxxxxxxxxxxxx.xxxxxxxxxxxxx")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie",
"1a9a93sda653=12a340a9c5d3e8sfd2161d0b; crmcsr=43sdv9-07ads5-4549-a166-0aad54gw6b; _zcsr_tmp=435e5334fa5-4549-a1667s889s8cf6b; JSESSIONID=54FF23B98378EBB45E4FA411823B5E61")
.build();
System.out.println("request = " + request);
try {
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println(i + "PrettyJson = " + prettyJsonString + "n______________end of string________");
JSONArray jsonArray = (JSONArray) json.get("data");
JSONObject data0 = (JSONObject) jsonArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
String id2 = data0.getString("id");
DNC_ID[i] = id2;
System.out.println("DNC_ID[" + i + "]= " + DNC_ID[i]);
} catch (Exception e) {
// Need to search leads by name if phone number does not work
// How to change the URL to search by name
System.out.println("Entered catch clause: index = " + i);
e.printStackTrace();
}
失败代码的输出:
request = Request{method=GET, url=https://www.zohoapis.com/crm/v2/Leads/search?phone=1234567890, tags={}}
Entered catch clause: index = 0
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:507)
at org.json.JSONObject.<init>(JSONObject.java:222)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.App.main(App.java:103)
您的代码无法解析某些JSON,这似乎不一定是因为搜索返回了零个结果。如果这是真的,它将返回一个空数组。仔细检查JSON形状,并确保它们与API返回的内容相匹配。
此外,看起来您正在混合和匹配两个不同的JSON库。像JSONObject
和谷歌的GSON这样的内置Android对象不会混合匹配。
为了帮助调试这一点,请使用日志系统中内置的OkHttps,并尝试设置不同的记录器级别。
为了帮助调试,您可以使用拦截器设置OkHttp调试日志记录。
Logger logger = LoggerFactory.getLogger(HttpUtil.class);
HttpLoggingInterceptor logging =
new HttpLoggingInterceptor((msg) -> {
logger.debug(msg);
});
logging.setLevel(Level.BODY);
client.addNetworkInterceptor(logging);