假设用户使用正确的凭据登录我的网站,结果是
{"ticketStatus":"Valid","requestId":"73","result":0,"resultText":"Valid"}
{"ticketStatus":"Invalid","requestId":"8","result":11,"resultText":"Invalid"}
如何做到这一点,以便我可以检索“有效/无效”或“ 0/11”,从而将用户发送到valid.html / invalid.html(其中包含您已成功/未成功登录) 。 如果它是“ invalid”或“ 11”(两者之一,取决于我可以分配的内容),也是如此。我只是不知道如何选择或将其放入if语句中。这是我的代码。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//index.html form user input
String fname = request.getParameter("firstName");
String lastName = request.getParameter("lname");
String ticketNummer = request.getParameter("ticketnr");
JsonParser parser = new JsonParser();
URL object=new URL(url);
String ticketCheck = "{\"function\":\"Check\",\"teamId\":\"IC106-2\",\"teamKey\":\"1b3741ccf6d9ec5245055370125d901e\",\"requestId\":\""+REQ_ID+"\",\"firstName\":\""+fname+"\",\"lastName\":\""+lastName+"\",\"ticketNumber\":\""+ticketNummer+"\"}";
System.out.println(ticketCheck);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(ticketCheck);
writer.flush();
StringBuilder sb = new StringBuilder();
String jsonResponseString = sb.toString();
JsonElement jsonTree = parser.parse(jsonResponseString);
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println("" + sb.toString());
} else {
System.out.println(con.getResponseMessage());
}
}
答案 0 :(得分:0)
通过解析响应解决了问题。
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println("" + sb.toString()); //the responsemessage
} else {
System.out.println(con.getResponseMessage());
}
String jsonStr = sb.toString();
JSONObject jsonObj = new JSONObject(jsonStr);
String ticketstat = jsonObj.getString("ticketStatus"); //get ticketStatus value
System.out.println(ticketstat);
if (ticketstat .equals("Invalid")){ //code here for w/e you want to do with invalid
}
}