// postToRestfulApi - // Note: params in the addr field need to be URLEncoded private String postToRestfulApi( String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try { URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { // System.out.println("Exception: " + e.getMessage()); } return result; } // TESTED
// callRestfulApi - Calls restful API and returns results as a string public String callRestfulApi( String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } } // TESTED
/** * Запрос с указанием параметров. * * @see MoneyDownloader#login * @see MoneyDownloader#password * @see MoneyDownloader#dateStart * @see MoneyDownloader#dateEnd */ public final void run() { File file = new File(directory + "/Results.tsv"); // File test = new File(directory + "/tmp/result.tsv"); try { if (!file.exists()) { file.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } String request = "https://rt.miran.ru?user="******"&pass="******"http://rt.miran.ru/rt/Search/Results.tsv?user="******"&pass="******"&Format=%27__Created__%2FTITLE%3A%D0%94%D0%B0%D1%82%D0%B0%27%2C%0A%27%20%20%20%3Cb%3E%3Ca%20href%3D%22%2Frt%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27__Subject__%2FTITLE%3A%D0%A2%D0%B5%D0%BC%D0%B0%27%2C%0A%27__QueueName__%2FTITLE%3A%D0%9E%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%27%2C%0A%27__CustomField.%7Binteraction%20type%7D__%2FTITLE%3A%D0%A2%D0%B8%D0%BF%27%2C%0A%27__CustomField.%7Bbussines%7D__%2FTITLE%3A%D0%91%D0%B8%D0%B7%D0%BD%D0%B5%D1%81%27%2C%0A%27__CustomField.%7Bdirection%7D__%2FTITLE%3A%D0%9D%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%27%2C%0A%27__CustomField.%7Bservice%7D__%2FTITLE%3A%D0%A3%D1%81%D0%BB%D1%83%D0%B3%D0%B0%27%2C%0A%27__CustomField.%7BSD%20Type%7D__%2FTITLE%3A%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F%27%2C%0A%27__CustomField.%7BSD%20Detail%7D__%2FTITLE%3A%D0%91%D0%BE%D0%BD%D1%83%D1%81%27%2C%0A%27__CustomField.%7BQA%7D__%2FTITLE%3A%D0%92%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=Created%7C%7C%7C&Page=1&Query=Created%20%3E%20%27" + dateStart + "%27%20AND%20Created%20%3C%20%27" + dateEnd + "%27%20AND%20Status%20%3D%20%27closed%27%20AND%20Queue%20!%3D%20%27manager%27%20AND%20Queue%20!%3D%20%27sales%27%20AND%20%27CF.%7BQA%7D%27%20%3D%20%27__CurrentUser__%27&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId="; System.out.println(tickets); ListCookieHandler cookieHandler = new ListCookieHandler(); CookieHandler.setDefault(cookieHandler); try { URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.getResponseCode(); GetMethod method = new GetMethod(tickets); method.addRequestHeader("Cookie", cookieHandler.getCookiez()); method.addRequestHeader("Referer", "http://rt.miran.ru/"); HttpClient httpClient = new HttpClient(); httpClient.executeMethod(method); InputStream in = method.getResponseBodyAsStream(); System.out.println(in.available()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override protected TicketItemResponse doInBackground(String... urls) { TicketItemResponse result = null; String uri = GV.URL + "/AddMenuItemToTicketServlet"; try { URL url = new URL(uri); CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId))); params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId))); params.add(new BasicNameValuePair("userId", String.valueOf(userId))); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder temp = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { temp.append((inputLine)); } in.close(); result = new Gson().fromJson(temp.toString(), TicketItemResponse.class); } catch (Exception e) { e.printStackTrace(); } return result; }
@Override public void execute() throws IOException { try { // Read the first 8192 bytes. // The full header should fit in here. // Apache's default header limit is 8KB. // Do NOT assume that a single read will get the entire header // at once! byte[] buf = new byte[BUFSIZE]; splitbyte = 0; rlen = 0; { int read = -1; try { read = inputStream.read(buf, 0, BUFSIZE); } catch (Exception e) { safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } if (read == -1) { // socket was been closed safeClose(inputStream); safeClose(outputStream); throw new SocketException("NanoHttpd Shutdown"); } while (read > 0) { rlen += read; splitbyte = findHeaderEnd(buf, rlen); if (splitbyte > 0) break; read = inputStream.read(buf, rlen, BUFSIZE - rlen); } } if (splitbyte < rlen) { inputStream.unread(buf, splitbyte, rlen - splitbyte); } parms = new HashMap<String, String>(); if (null == headers) { headers = new HashMap<String, String>(); } // Create a BufferedReader for parsing the header. BufferedReader hin = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, rlen))); // Decode the header into parms and header java properties Map<String, String> pre = new HashMap<String, String>(); decodeHeader(hin, pre, parms, headers); method = Method.lookup(pre.get("method")); if (method == null) { throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error."); } uri = pre.get("uri"); cookies = new CookieHandler(headers); // Ok, now do the serve() Response r = serve(this); if (r == null) { throw new ResponseException( Response.Status.INTERNAL_ERROR, "SERVER INTERNAL ERROR: Serve() returned a null response."); } else { cookies.unloadQueue(r); r.setRequestMethod(method); r.send(outputStream); } } catch (SocketException e) { // throw it out to close socket object (finalAccept) throw e; } catch (SocketTimeoutException ste) { throw ste; } catch (IOException ioe) { Response r = new Response( Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage()); r.send(outputStream); safeClose(outputStream); } catch (ResponseException re) { Response r = new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); r.send(outputStream); safeClose(outputStream); } finally { tempFileManager.clear(); } }