Spring Servlet HTTP Post request re-send - java

I'm having a bit of an design and coding problem.
Step1: I receive an http post request which i save into my db.
2: then i need to resend the the same request.
3: return the form of the external url. simple jsp side with a redirect to the target_URL (I think thats inconvenient but i'm not sure how else to do that.
My problem is that I'm sending an http post request to an url where i redirect my application user. what would be a better solution. should i send it with my jsp? but how can i get my data there.
problem #2: is my way to send the post request correct ?
Thx for any help, I'm kinda lost or blocked today ;)
#RequestMapping("/internalData")
public String paymentReceiveInternal(HttpServletRequest request)
throws ServletException, IOException {
User user = new User();
user.setUserName(request.getParamter("name");
//save user into DB
// resend the request.
URL targetUrl = new URL(VIEW_TARGET_URL);
HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(request.getContentLength()));
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(urlParameters);
writer.flush();
writer.close();
connection.disconnect();
return VIEW_TARGET_URL;

Related

I am confused about something in python to send an HTTP request that I am trying to recreate in java

My friend recently sent me this code:
requests.post("example.com", headers = {'authorization': token}, json = {'content' : message})
it is in python. It is meant to send an HTTP post request to example.com and I am trying to convert it to java.
So far, I have this:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//url is defined farther up in the code.
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", token);
However, in my friends code he had 2 different parts that were headers={} and json={}
I don't know how I would do this in java. I am confused what the difference between headers and json is. How would I choose the content of the message? please let me know.
So from what I understand you having issues adding the json content to the request?
setRequestProperty() in java is the same in python as doing the following:
headers = {}
headers['Content-Type'] = "application/json"
headers['Authorization'] = token
I haven't written in Java for a long time but from what I have read you need to do the following:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Authorization", token);
connection.setDoOutput(true);
// This part sends the json data to the output stream with the headers defined above sent with the data
String inputString = "{variable1: "myvariable1", variable2; "myvariable2"}";
try(OutputStream stream = con.getOutputStream()){
byte[] input = inputString.getBytes("utf-8");
stream.write(input, 0, input.length);
}
You are already setting the headers via "setRequestProperty()" you just need to send the data as well.

Java doesn't send HTTP POST Request

I'm implementing some simple java class in order to send an HTTP Request with POST method and also another java class in order to receive it.
The server works fine when I make a POST request by means of my browser(Chrome), or an application(I have used Postman in this case) but it ends up with problem when I send HTTP Request with java!
My sending HTTP class is "Sender.java", containing the following snippet:
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic post request
con.setRequestMethod("POST");
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//con.setRequestProperty("Content-Type","text/plain");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();
os.close();
//connect to the Server(resides at Server.java)
con.connect();
I have commented some lines of code setting Headers like "Accept-Language" and "Content-Type" because I don't know whether or not are these headers required for the java program to work out?
The server is another java program named "Server.java". Here is the snippet related to reading HTTP Request made by the Sender.java(if need be).
int servPort = 8082;
// Create a server socket to accept HTTP client connection requests
HttpServer server = HttpServer.create(new InetSocketAddress(servPort), 0);
System.out.println("server started at " + servPort);
server.createContext("/", new PostHandler());//PostHandler implements HttpHandler
server.setExecutor(null);
server.start();
All I want is to send a plaintext as the body of my HTTP Request with the Post method. I have read plenty of sites and even related questions at this site. But it still doesn't work out. In other words, whenever I create an HTTP Request from "Sender.java", nothing appears at "Server.java". I just want to know what's wrong with my snippets and how should I fix that?
I tested this and it's working:
//Sender.java
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write("Just Some Text".getBytes("UTF-8"));
os.flush();
int httpResult = con.getResponseCode();
con.disconnect();
As you can see, connect is not necessary. The key line is
int httpResult = con.getResponseCode();
When you send a POST form using the browser, it sends the form in a certain format, defined in RFC1866, you have to recreate this on Java when making a post request.
With this format, its important you set the Content-Type header to application/x-www-form-urlencoded, and pass the body as you would do in a url with a get request.
Borrowing some code of my previous answer to POST in Java:
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic post request
con.setRequestMethod("POST");
Map<String,String> form = new HashMap<>();
// Define the fields
form.put("username", "root");
form.put("password", "sjh76HSn!"); // This is a fake password obviously
// Build the body
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
// Prepare our `con` object
con.setFixedLengthStreamingMode(length);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.connect();
try (OutputStream os = con.getOutputStream()) {
os.write(out);
}
Maybe “localhost” in the sender url does not resolve to the same ip that the server binds to? Try changing to 127.0.0.1 or your actual IP address.
try with PrintStream
String url = "http://localhost:8082/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic post request
con.setRequestMethod("POST");
//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//con.setRequestProperty("Content-Type","text/plain");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
java.io.PrintStream printStream = new java.io.PrintStream(os);
printStream.println("Just Some Text");
con.getInputStream();//Send request
os.flush();
os.close();

HTTP POST is not working from Java

I am trying to do an http post. Same code was working.But now it is not hitting my servlet now, but giving http response code 200. From browser same url is hitting the servlet. Is there anything that restricting my post?. Please help me on it. Sorry for bad english.
int timeout=3000;
String url="http://localhost:8020/WiCodeDynamic/WiCode?json=";
String requestUrl="{\"vspCredentials\":{\"id\":\"TET\",\"password\":\"test\"}}";
URL x = new URL(url);
HttpURLConnection connection =(HttpURLConnection)x.openConnection();
connection.setRequestMethod("POST");
//;charset=utf-8
connection.setRequestProperty("Content-type","application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(timeout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bw.write(requestUrl);
bw.flush();
int resp_code = connection.getResponseCode();
String resp_msg = connection.getResponseMessage();
System.out.println("resp_code="+resp_code);
System.out.println("resp_msg="+resp_msg);
brs,
Only a minor mistake. Move the json= from the end of your URL to the beginning of your POST request (requestUrl) and you should be fine.
Also I suggest you use URLEncoder.encode to escape the string you are transfering properly.

HTTP POST request in java - setting content length

Below is my code which does POST request to login to a website. When i run the same I receive Message response as 411. Can anybody help me to set the correct Content Length?
try {
String request = "http://<domain.com>/login";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Content-Length", "1");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("email", "abc");
connection.setRequestProperty("password", "xyz");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
int code = connection.getResponseCode();
System.out.println("Response Code of the object is " +code);
if(code == 200)
System.out.println("OK");
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok - you're not moving anything into the body of the request so you should set the length to "0".
Add:
connection.connect();
after:
connection.setRequestMethod("POST");
google "httpurlconnection post parameters" for adding parameters to a POST request. This site has at least four or five solutions.
Although the answer might be too late, but just for future reference.
I faced exactly the same problem and for the reasons already mentioned I kept getting the same error.
I managed to work around the problem by sending just an empty body:
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = "".getBytes("utf-8");
os.write(input, 0, input.length);
}
That fixed the issue for me. Manually setting the Content-Length header does not help as already mentioned.
I was facing the same problem. I was trying to send a POST request with an empty body, but the request was rejected by the server, returning 411.
Then I found the following code in 'sun.net.www.protocol.http.HttpURLConnection', which is the implementation of 'java.net.HttpURLConnection':
private static final String[] restrictedHeaders = new String[]{"Access-Control-Request-Headers", "Access-Control-Request-Method", "Connection", "Content-Length", "Content-Transfer-Encoding", "Host", "Keep-Alive", "Origin", "Trailer", "Transfer-Encoding", "Upgrade", "Via"};
So, when you set a header via sun.net.www.protocol.http.HttpURLConnection.setRequestProperty, if the key is included in the array above, it will be ignored. That's why setting 'Content-Length' manually is not working.

HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set

Here is my code:
String addr = "http://172.26.41.18:8080/domain/list";
URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.setRequestMethod("GET");
httpCon.addRequestProperty("Authorization", "Basic YWRtaW4fYFgjkl5463");
httpCon.connect();
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();
What I see in response:
500 Server error
I open my httpCon var, and what I see:
POST /rest/platform/domain/list HTTP/1.1
Why is it set to POST even though I have used httpCon.setRequestMethod("GET"); to set it to GET?
The httpCon.setDoOutput(true); implicitly set the request method to POST because that's the default method whenever you want to send a request body.
If you want to use GET, remove that line and remove the OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream()); line. You don't need to send a request body for GET requests.
The following should do for a simple GET request:
String addr = "http://172.26.41.18:8080/domain/list";
URL url = new URL(addr);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setUseCaches(false);
httpCon.setAllowUserInteraction(false);
httpCon.addRequestProperty("Authorization", "Basic YWRtaW4fYFgjkl5463");
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
See also:
Using java.net.URLConnection to fire and handle HTTP requests
Unrelated to the concrete problem, the password part of your Authorization header value doesn't seem to be properly Base64-encoded. Perhaps it's scrambled because it was examplary, but even if it wasn't I'd fix your Base64 encoding approach.

Categories