I am not able to send through a POST method in java parameters using the HttpURLConnection. I've been trying in a few ways and researched a lot, but no way worked for me. I will leave the code below for you to indicate possible modifications that can be made.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpTeste {
private final String USER_AGENT = "Mozilla/5.0";
public void sendPost(String url) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "idRoute=1";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
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());
}
}
As you can see, I tried to send the parameters of my request through urlParameters
, but it still did not work. The code runs and does not acknowledge any errors, but it does not return a response that should return.
I also tried to send the parameters through String urlParameters = URLEncoder.encode ("idRoute", "UTF-8") + "=" + URLEncoder.encode ("1", "UTF-8");
wr.writeBytes(urlParameters);
But it also did not work, thank you for the collaboration of all!