I'm trying to use an existing API that calls for a json object to be "submitted" using POST, but the page also requires a few parameters in request, for this example we will use name, and email. I'm super new to REST so I'm probably making an ignorant mistake somewhere here.
Here is the code I have so far in my servlet:
String path = "http://www.test.com/submit";
URL url = new URL(path);
conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
Gson gson = new Gson();
//julySchedule is the object I want to submit with this request alongside the parameters.
String input = gson.toJson(julySchedule);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("HTTP POST Request Failed with Error code : "
+ conn.getResponseCode());
}
I've tried to put the parameters in the URL, like:
/submit?name=Name&email=test#gmail.com
But that didn't work, because POST requests wont accept parameters like that.
Then I tried to add it to the Output stream like:
String params = "name=Name&email=test#gmail.com"
OutputStream os = conn.getOutputStream();
os.write(path.toBytes());
os.write(input.getBytes());
os.flush();
But that didn't work either. Am I making a really dumb mistake somewhere?
It is perfectly fine for a POST request to contain query string(Though not best practice).
Since you use application/json as Content-Type, I assume your payload has to be a JSON object. You cannot mix your params in POST body. You have 2 options:
Kep email&name in QueryString, and json in POST payload: What you did should work.
Use POST payload only: Set Content-Type: application/x-www-form-urlencoded as follows: name=NAME&email=EMAIL&jsonPayLoad={Your Json Object}. Server should extract jsonPayLoad from POST payload.
Make sure to escape using encodeURIComponent before writing to POST output stream.
Related
I'm having problems doing a Postman REST call copying a REST call in Java.
I tried to set request properties on Postman the same way they're set in Java, but it's not working.
I have to send a base64 string with this call (i put in italic the code line where this is done in Java code)
URLConnection connection = new URL(url + content).openConnection();
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(timeout);
((HttpURLConnection) connection).setRequestMethod("POST");
connection.setRequestProperty("Accept", "*/*");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStream output = connection.getOutputStream();
JSONObject conf = new JSONObject();
conf.put("signedEvidence", String.format("%s", baos));
*output.write(conf.toString().getBytes());*
output.flush();
checkHttpStatus(connection);
I configured Postman like this:
And i receive this answer:
EDIT - In few words: the REST call works fine in Java, but i need to do some of these calls in Postman with my own variable (the service i'm calling do some works with base64 string i pass him).
EDIT2 - Main problem, in my opinion, is the line:
output.write(conf.toString().getBytes());
which set the base64 in my Java call, and i don't understand/know how to do the same in my Postman call.
Try only adding the following values:
Then, add the content type and the values which you need to pass.
What I need to do is send POST request to specific URL with two parameters and when the request is sent, I need to redirect user to that link so that he would be able to access functionality.
So far, what I have managed to do from various examples is this:
private void postRemoteAdvisoryLink() throws IOException {
URL obj = new URL(KdrmApplicationContext.getRemoteAdvisoryUrlPath());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For post only - start
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("?auth=ssor&TransportKey=" + ssorTransportKey).getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
}
The problem is that now I get connection time out when trying to execute OutputStream os = con.getOutputStream(); line. Also, I still have no idea how to redirect user when request is completed.
Any ideas?
Using the basic Java URL classes would require you to manually handle the details of HTTP protocol - it's better to use libraries like Apache Http Components, as they deal with the underlying protocols for you. Some examples including POST requests can be found on their website.
Given the original question, the Timeout is likely related to host not responding or your Java application being unable to connect to given URL (due to no proxy configuration for example).
If you want to redirect a request based on the answer, you need to check the response headers and http status - if the status is 302, then there should be a header called Location, which will contain the URL you should make another request to.
Before getting an OutputStream, also make sure to set the Content-Length header (and ideally the Content-Type header as well).
I requested to send some parameters from java file using post method. I did
String urlParameters = "param1=a¶m2=b¶m3=c";
URL url = new URL("http://testing/index.jsp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
But from receiver's end asks me to send it in body instead of url parameter. I am not sure what I am doing wrong. Please explain me how this code will work and what changes has to be done if I want to send info in request body.
i believe you either need to call the connect() method on the URLConnection at the end, or call a method that would cause the connect to be called for you, like fetching the resulting input stream.
Also you should think about what format the body should be in. Often people like to use standard formats like json, but you will have to decide that between you and the people implementing the server.
I am making a POST Request to a server with Content-Type set to application/x-www-form-urlencoded. One of the query parameter has a value which contains & in it. I replace the & with & before sending the request.
When I send this request using POSTMAN (Chrome Extension), the request goes fine and I receive the expected response. But when I send this request using a Java application, the server throws an error (unable to parse document). Here is the code that I'm using to send the request:
URL url = new URL(url); // url => "http://myserver.com/api/update"
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(60000);
urlConnection.setReadTimeout(60000);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
printWriter.print(params); // params => api_key=abcd123&update_data_id=123&update_data_value=Test&Value
printWriter.flush();
InputStream inputStream = urlConnection.getInputStream();
String contentType = urlConnection.getContentType();
FileUtil.closeWriter(printWriter);
// Parse response ...
Here, the problem occurs in the parameter update_data_value. If I remove the &, the request goes fine from both, POSTMAN as well as my application. But when the & is present, only the request through POSTMAN works fine.
What could be wrong ?
Thanks a lot for your help!
After a long conversation in chat, the problem was this:
It's about a XML string, where an ampersand is used. The ampersand needs to replaced with "&", according to the XML-Standard.
This XML string needs to be sent in a POST request, so the ampersand and likely the semicolon need to be escaped.
The final replacement string looks like this: "%26amp%3B".
I am trying to make a HTTPS call using Java to a browser that uses the native login prompt.
http://blog.stevensanderson.com/2008/08/25/using-the-browsers-native-login-prompt/
Currently I'm using the below for HTTP and it works fine for other websites since I know the parameters to put in...however it fails for the above type of login (I am not sure how to capture the parameters...it's a login pop up..or if this is even the correct approach)....any ideas??..thanks
HttpUtility.sendPostRequest(requestURL, params);
String[] response = HttpUtility.readMultipleLinesRespone();
The server should respond to your first request with a WWW-Authenticate header and a status of 401. The header will contain details of the kind of authentication it's expecting.
Then you can try again after adding an Authorization header to your request in the correct format.
#alex: OK...I managed to make the HTTPS connection following your suggestion with this:
URL url = new URL("https://www.example.com/Login");
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authString);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
//then I read the input stream..
But when I tried to make another connection (say go to a different page after login) with this code in another method...taking URLConnection as the parameter:
//Below is in a method called account(URLConnection urlConnection)
URL url = new URL("https://www.example.com/account.aspx");
urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
//again I read the input stream..
...it throws the below exception...same exception before logging in..how can I rectify?
Server returned HTTP response code: 401 for URL: https://www.example.com/account.aspx
You have probably moved on from this problem, but I recently had an issue that involved achieving functionality similar to the browser's native login prompt. I have solved it and written a post about it. Steven Sanderson's post was helpful for me too, in helping me understand certain concepts.
http://captaindanko.blogspot.com.au/2015/04/how-does-browsers-native-login-prompt.html