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.
Related
I have a short Android-Java client program which sends a basic information to bottle-python server with POST method. In the first version of code, server does not show anything. However, In the second version it works but I cannot understand what this additional line do because it has anything to do with posting content. I really appreciate if someone helps me figure this out.(There is nothing wrong with the server code since I can properly send request with python requests and my browsers).
This is the first version of client code:
String url = "http://192.168.1.23:8080/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
PrintStream myPusher = new PrintStream(os );
myPusher.print("param1=hey");
Second version:
String url = "http://192.168.1.23:8080/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
PrintStream myPusher = new PrintStream(os );
myPusher.print("param1=hey");
InputStream in= con.getInputStream(); //Nothing changed but only this additional line
Bottle(python) server:
#app.route('/', method="POST")
def hello():
print("it works")
name = request.forms.get("param1")
print(name)
return name
#app.route('/')
def hello():
i=0
print("it works")
run(app, host="192.168.1.23", port=8080)
With first client code server shows nothing.
With second code server shows:
it works
hey
192.168.1.24 - - [31/Dec/2018 17:10:28] "POST / HTTP/1.1" 200 3
Which is as I expected.
With your first code snippet the output stream is still open. So the server does not know if it got the complete request. Probably just closing the stream would work as well.
However, I would make at least a call to getResponseCode to see the outcome of the request.
Your java code seems incomplete for sending a post request.
I think by using this code, you can make it work for yourself.
The PrintStream is a buffered type, this means you should add a flush operation after each print(), or use println() instead.
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.
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".
How to pass input to a php web page using a automated script ,i.e. i just want to know how pass arguments to text fields using a script. like passing input to username and password field of a web page and then pressing submit button(that too with a script).
favorable language: JAVA
Try Selenium. Selenium is great at automating web browsers.
http://seleniumhq.org/
Also has pure support with Java. But not only.
When it comes to custom methods, see ...
String urlParameters = "param1=a¶m2=b¶m3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.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(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
source (Java - sending HTTP parameters via POST method easily)
if you web page uses the GET method to accept data (i.e. from URL), just connect to the web pages giving the data you want to pass:
http://www.mysite.com/mypage.html?data0=data0,data1=data1
if the web page uses POST things get a little bit more complicated: you have to forge an appropriate HTML request with all your data in the header (as POST method requires)
You can use the Apache HTTPClient - see the example at:
http://hc.apache.org/httpclient-3.x/methods/post.html
This allows you to simulate submitting a fully filled form directly to the destination page and grab the results.
Remember that, after the call, you have to grab and store the session cookie in the response and resubmit it to the following pages you want to "visit" to stay "logged on"
I would like to show how I would do to pass an input to the HTML. I usually use python to send request to the page where I need to input the data. Before doing that you need to know if you need to supply web-cookies or not, if yes, copy the cookie, if you need to be logged in otherwise not, just check that. Once that is done, you need to know the field names for the input area as you will be using them to POST or GET data using your script. Here is sample usage.
import urllib
import urllib2
import string
headers = {'Cookie': 'You cookies if you need'}
values = {'form_name':'sample text', 'submit':''}
data = urllib.urlencode(values)
req = urllib2.Request('website where you making request to',data,headers)
opener1 = urllib2.build_opener()
page1=opener1.open(req)
#OPTIONAL
htmlfile=page1.read()
fout = open('MYHTMLFILE.html', "wb")
fout.write(htmlfile)
fout.close()