When I try and send a request to my server, the server only gets POST requests no matter if I set setRequestMethod("GET") . This is the function I am calling, with an url and 2 params I need to send with them:
public static String getHTML(String urlToRead,String urlParameters) {
try {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
conn.setUseCaches(false);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (
conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
catch (Exception e) {
return e.getMessage().toString();
}
}
}
Any help is welcome or any other functions to be able to send a GET request to a server by sending the URL and two parameters.
Do it as follows:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
class Main {
public static void main(String[] args) {
System.out.println(getHTML("http://localhost:8080/TestDynamicProject/getdata.do?t1=tp1&t2=tp2"));
}
public static String getHTML(String urlToRead) {
try {
StringBuilder result = new StringBuilder();
InputStream stream = null;
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = conn.getInputStream();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
} catch (Exception e) {
return e.getMessage().toString();
}
}
}
Output:
Response from GET | Request parameters: t1=[tp1],t2=[tp2]
Given below is my Servlet
:
@WebServlet("/getdata.do")
public class TestServlet extends HttpServlet {
public TestServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
request.getParameterMap().forEach((k, v) -> sb.append(k.toString() + "=" + Arrays.toString(v) + ","));
sb.deleteCharAt(sb.length() - 1);
response.getWriter().append("Response from GET").append(" | Request parameters: ").append(sb);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Response from POST");
}
}