Commit 4aeae7c2 authored by kiana's avatar kiana

saving and response to requests again is improved

parent f243ea99
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.util.stream.Stream;
public class Fire {
GetResponse savedRequests;
File[] files;
public Fire() {
}
public void fire(int i) {
i--;
if (files[i].getName().contains(".txt")) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(files[i]));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String content = null;
try {
content = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(content);
savedRequests = new GetResponse(content);
}
}
public void showRequest(){
int count = 0;
for (File file : files) {
if (file.getName().contains(".txt") && file.getName().contains(".txt")) {
count++;
System.out.println();
System.out.print(count+" . ");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String content = null;
try {
content = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(content);
String[] contentCopy = content.trim().split(" ");
for (int i = 0; i < contentCopy.length; i++) {
if (contentCopy[i].contains("http://")) {
System.out.print("url: " + contentCopy[i] + "| ");
}
if (contentCopy[i].equals("-M") || contentCopy[i].equals("--method")) {
System.out.print("method: " + contentCopy[i + 1] + "| ");
} else if (contentCopy[i].equals("-H") || contentCopy[i].equals("--headers")) {//setting headers
String[] keyValue = contentCopy[i + 1].trim().split(";");//splitting headers from each other
System.out.print("headers: ");
for (int j = 0; j < keyValue.length; j++) {
String[] keyValueCopy = keyValue[j].trim().split(":");//splitting key and value
String key = keyValueCopy[0];
String value = keyValueCopy[1];
System.out.print(key + ": " + value + "/");
}
i++;
} else if (contentCopy[i].equals("-i")) {
System.out.println("include headers: true" + "| ");
} else if (contentCopy[i].equals("-O") || contentCopy[i].equals("--output")) {
System.out.println("output: true" + "| ");
} else if (contentCopy[i].equals("-d") || contentCopy[i].equals("--data")) {
String cont = contentCopy[i + 1];
System.out.print("messageBody: " + cont + "| ");
}
}
}
}
System.out.println();
}
}
\ No newline at end of file
import javax.imageio.IIOException; import javax.imageio.IIOException;
import java.io.IOException; import java.io.*;
import java.net.HttpURLConnection; import java.net.*;
import java.net.ProtocolException; import java.net.http.HttpHeaders;
import java.net.URL;
import java.util.HashMap; import java.util.HashMap;
import java.util.Scanner; import java.util.Scanner;
import java.nio.file.Files; import java.nio.file.Files;
import java.io.File;
import java.io.FileWriter;
import java.net.URLEncoder;
import java.util.Map; import java.util.Map;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class GetResponse {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home"; public class GetResponse {
private static final String POST_PARAMS = "userName=Pankaj";
Map<String, String> params = new HashMap<>(); Fire fire = new Fire();
//params.put("v", "dQw4w9WgXcQ"); Boolean include = false;
String requestMethod;
String headers;
Boolean invisible;
String help; String help;
String arg; String arg;
String address; String address;
String completeRequest; String completeRequest;
String content; String content;
Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in);
HttpURLConnection con;
URL obj1;
public GetResponse(){ public GetResponse() {
splitRequest(); String[] copy = splitRequest();
try { try {
response(); response(copy);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public GetResponse(String requestAgain){
completeRequest = requestAgain;
String[] copy = requestAgain.trim().split(" ");
address = copy[0];
try {
response(copy);
} catch (IOException e) {
e.printStackTrace();
}
}
public String[] splitRequest() { public String[] splitRequest() {
completeRequest = scanner.next(); completeRequest = scanner.nextLine();
String[] splittedRequest = completeRequest.split("\\s"); String[] splitRequest = completeRequest.trim().split(" ");
address = splittedRequest[0]; address = splitRequest[0];
return splittedRequest; for (String test: splitRequest)
{
System.out.println(test);
}
return splitRequest;
}
public void save(String fileName, String str) throws IOException {
System.out.println(str);
File file = new File(fileName);
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(str);
writer.close();
File temp = File.createTempFile("file", ".txt", file.getParentFile());
String delete = "-S";
String deleteSave = "--save";
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writerForDelete = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null; ) {
line = line.replace(delete, "");
line = line.replace(deleteSave, "");
writerForDelete.println(line);
}
reader.close();
writerForDelete.close();
file.delete();
temp.renameTo(file);
}
public void responseHeader(){
con.getHeaderField(2);
}
public void savedList(){
// try-catch block to handle exceptions
try {
File file = new File("/Users/kiana/Courses/2nd Semester/javva projects/CurlInsomnia");
fire.files = file.listFiles();
fire.showRequest();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public boolean isMethod(String test){
return test.equals("GET") || test.equals("POST") || test.equals("HEAD")
|| test.equals("DELETE") || test.equals("PUT") || test.equals("CONNECT")
|| test.equals("OPTIONS") || test.equals("TRACE") || test.equals("PATCH");
}
public HttpURLConnection connect(URL url, String requestType, HttpURLConnection connection) {
try {
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
connection.setRequestMethod(requestType);
}
return connection;
} catch (IOException e) {
System.out.println("E" + e.getMessage());
return null;
}
}
public void post(HttpURLConnection conn, String content){
conn.setDoOutput(true);
OutputStream os = null;
try {
os = conn.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(os, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
osw.write(content);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
} }
try {
os.close();
} catch (IOException e) {
}
}
public void response() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
public void response(String[] splitRequestCopy) throws IOException {
if (!completeRequest.contains("http://") && completeRequest.contains("list")){
savedList();
String fireRequest = scanner.nextLine();
String[] requestsAgain = fireRequest.split(" ");
for (int i = 2; i < requestsAgain.length; i++){
fire.fire(Integer.parseInt(requestsAgain[i]));
}
return;
}
try {
String link_url = address;
obj1 = new URL(link_url); //URL Connection Created...
con = (HttpURLConnection) obj1.openConnection(); //Http URL Connection Created...
System.out.println(address);
con.setRequestMethod("GET"); con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
StringBuilder requestData = new StringBuilder(); for (int i = 0; i < splitRequestCopy.length ; i++) {
if (splitRequestCopy[i].equals("-M") || splitRequestCopy[i].equals("--method")) {
if (isMethod(splitRequestCopy[i + 1])) {
con = connect(obj1, splitRequestCopy[i + 1], con);
System.out.println(con.getRequestMethod());
System.out.println("44444444444");
i++;
for (Map.Entry<String, String> param : params.entrySet()) {
if (requestData.length() != 0) {
requestData.append('&');
} }
// Encode the parameter based on the parameter map we've defined
// and append the values from the map to form a single parameter
requestData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
requestData.append('=');
requestData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
} }
else if (splitRequestCopy[i].equals("-H") || splitRequestCopy[i].equals("--headers")) {//setting headers
String[] keyValue = splitRequestCopy[i + 1].trim().split(";");//splitting headers from each other
for (int j = 0; j < keyValue.length; j++){
String[] keyValueCopy = keyValue[j].trim().split(":");//splitting key and value
String key = keyValueCopy[0];
String value = keyValueCopy[1];
//con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty(key, value);
System.out.println("55555555");
// Convert the requestData into bytes }
byte[] requestDataByes = requestData.toString().getBytes("UTF-8"); i++;
}
else if (splitRequestCopy[i].equals("-i")) {
System.out.println("33333333");
include = true;
}
String[] splittedRequestCopy = splitRequest(); else if (splitRequestCopy[i].equals("-S") || splitRequestCopy[i].equals("--save")){
for (int i = 0; i < splittedRequestCopy.length - 1; i++) { Random random = new Random();
if (splittedRequestCopy[i].equals("-M") || splittedRequestCopy[i].equals("--method")) { int k = random.nextInt(100000);
if (splittedRequestCopy[i + 1].equals("GET") || splittedRequestCopy[i + 1].equals("POST") || splittedRequestCopy[i + 1].equals("HEAD") String requestName = "savedRequest" + k + ".txt";
|| splittedRequestCopy[i + 1].equals("DELETE") || splittedRequestCopy[i + 1].equals("PUT") || splittedRequestCopy[i + 1].equals("CONNECT") save(requestName, completeRequest); //saving the whole request ????????
|| splittedRequestCopy[i + 1].equals("OPTIONS") || splittedRequestCopy[i + 1].equals("TRACE") || splittedRequestCopy[i + 1].equals("PATCH")) }
con.setRequestMethod(splittedRequestCopy[i + 1]);
} else if (splittedRequestCopy[i].equals("-H") || splittedRequestCopy[i].equals("--header")) {
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Content-Length", String.valueOf(requestDataByes.length));
} else if (splittedRequestCopy[i].equals("-i")) { else if (splitRequestCopy[i].equals("-O") || splitRequestCopy[i].equals("--output")) {
invisible = true;
} else if (splittedRequestCopy[i].equals("-O") || splittedRequestCopy[i].equals("--output")) {
try { try {
if (!isMethod(splitRequestCopy[i + 1])) {
content = con.getResponseMessage(); content = con.getResponseMessage();
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -107,10 +250,49 @@ public class GetResponse { ...@@ -107,10 +250,49 @@ public class GetResponse {
iox.printStackTrace(); iox.printStackTrace();
} }
} }
content = con.getResponseMessage();
System.out.println(content); else if (splitRequestCopy[i].equals("-d") || splitRequestCopy[i].equals("--data")){
int code = con.getResponseCode(); String cont = splitRequestCopy[i];
System.out.println(code); post(con, cont);
}
else if (splitRequestCopy[i].equals("-h") || splitRequestCopy[i].equals("--help")){
String help = ("-d, --data DATA HTTP POST data (H)" +
"\n" + "-H, --header LINE Pass custom header LINE to server (H)"
+ "\n" + "-h, --help This help text" +
"\n" + "-i Include protocol headers in the output (H/F)"
+"\n" + "-o, --output FILE Write to FILE instead of stdout" +
"");
System.out.println(help);
return;
}
}
con.setInstanceFollowRedirects(true);
con.connect();
//getting the response
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer responseBuffer = new StringBuffer();
String lines;
while ((lines = in.readLine()) != null){
responseBuffer.append(lines + "\n");
}
in.close();
System.out.println("Connection Response Message : "+con.getResponseMessage());
System.out.println("RESPONE:" + con.getRequestMethod());
System.out.println(con.getResponseCode());
System.out.println(responseBuffer.toString());
if (include)
responseHeader();
con.disconnect();
}
catch (Exception e) {
System.out.println( e);
} }
} }
} }
import java.io.IOException; import java.io.IOException;
import java.net.*;
import java.util.Scanner;
import java.util.Scanner;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main { public class Main {
public static void main(String[] args){ public static void main(String[] args) throws IOException {
// GetResponse getResponse = new GetResponse();
// getResponse.splitRequest();
// Response response = new Response();
GetResponse response = new GetResponse(); GetResponse response = new GetResponse();
} }
} }
import java.io.BufferedReader; // Import required java libraries
import java.io.IOException; import java.io.*;
import java.io.InputStreamReader; import javax.servlet.*;
import java.io.OutputStream; import javax.servlet.http.*;
import java.net.HttpURLConnection; import java.util.*;
import java.net.URL;
public class Response { // Extend HttpServlet class
public class Response extends HttpServlet {
// Method to handle GET method request.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
private static final String USER_AGENT = "Mozilla/5.0"; // Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
private static final String GET_URL = "https://localhost:9090/SpringMVCExample"; // Set response content type
response.setContentType("text/html");
private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home"; // Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
private static final String POST_PARAMS = "userName=Pankaj"; if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
public Response (){ String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
try { PrintWriter out = response.getWriter();
sendGET(); String title = "Auto Refresh Header Setting";
} catch (IOException e) { String docType =
e.printStackTrace(); "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
}
System.out.println("GET DONE");
try {
sendPOST();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("POST DONE");
}
private static void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { out.println(docType +
response.append(inputLine); "<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
} }
in.close();
// print result // Method to handle POST method request.
System.out.println(response.toString()); public void doPost(HttpServletRequest request, HttpServletResponse response)
} else { throws ServletException, IOException {
System.out.println("GET request not worked");
}
doGet(request, response);
} }
private static void sendPOST() throws IOException {
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment