【发布时间】:2021-03-23 00:07:03
【问题描述】:
所以我请求 API 调用以通过电话号码搜索记录。如果响应不成功,我想更改 URL 以按名称搜索记录。为了发送请求并获得响应,我们有一个 try catch 子句。我唯一的想法是使用原始 catch 子句中的新 URL 重复请求和响应。如果原始请求捕获异常,任何人都可以告诉我应该如何更改 URL 并发出新请求。这是我请求按电话号码搜索的代码的 sn-p。以及由于请求失败而明显的stackstrace。
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)
【问题讨论】:
标签: java api exception try-catch okhttp