I have a web backend, which works with the following jQuery post:
$.post(path + "login",
{"params": {"mode":"self", "username": "aaa", "password": "bbb"}},
function(data){
console.log(data);
}, "json");
How can I implement the same POST from Java, with HttpURLConnection? I'm trying with
URL url = new URL(serverUrl + loginUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length",
Integer.toString(postData.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr =
new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(postData);
wr.flush ();
wr.close ();
BufferedReader br =
new BufferedReader(
new InputStreamReader(connection.getInputStream()));
, where postData = "{\"mode\": \"...\", ..... }"
but it doesn't work the same way.
The code on the server is written id Django, and tries to get the data in this way:
mode=request.POST.get("params[mode]")
You seem to be thinking all the time that jQuery sends JSON in its raw form to the server and that the HTTP server flawlessly understands it. This is not true. The default format for HTTP request parameters is application/x-www-form-urlencoded, exactly like as HTML forms in HTTP websites are using and exactly like as how GET query strings in URLs look like: name1=value1&name2=value2.
In other words, jQuery doesn't send JSON unmodified to the server. jQuery just transparently converts them to true request parameters. Pressing F12 in a sane browser and inspecting the HTTP traffic monitor should also have shown you that. The "json" argument which you specified there in end of $.post just tells jQuery which data format the server returns (and thus not which data format it consumes).
So, just do exactly the same as jQuery is doing under the covers:
String charset = "UTF-8";
String mode = "self";
String username = "username";
String password = "bbb";
String query = String.format("%s=%s&%s=%s&%s=%s",
URLEncoder.encode("param[mode]", charset), URLEncoder.encode(mode, charset),
URLEncoder.encode("param[username]", charset), URLEncoder.encode(username, charset),
URLEncoder.encode("param[password]", charset), URLEncoder.encode(password, charset));
// ... Now create URLConnection.
connection.setDoOutput(true); // Already implicitly sets method to POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
// ... Now read InputStream.
Note: do NOT use Data(Input|Output)Stream! Those are for creating/reading .dat files.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
You should use efficient libraries to build (valid) json objects. Here is an example from the PrimeFaces library:
private JSONObject createObject() throws JSONException {
JSONObject object = new JSONObject();
object.append("mode", "...");
return object;
}
If you wish to have a nice and clean code to send and retrieve objects, take a look at the answer from Emil Adz ( Sending Complex JSON Object ).
Related
I request POST by this code
URL url = new URL("adress/discordnotifi");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
JSONObject object = new JSONObject();
myPWord = ((EditText) (findViewById(R.id.edit_Id))).getText().toString();
object.put("token", tokens);
object.put("discordid", mydiscord);
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(object.toString().getBytes("UTF-8"));
Log.d("debug",object.toString());
outputStream.flush();
outputStream.close();
and my tokens and mydiscord is the information that I want to send as JSON format like
{"token":"tokens","discordid":"mydiscord"}
and from python flask
#app.route('/discordnotifi', methods=['POST'])
def post():
content = request.json
print(content)
Discordid = int(content["discordid"])
token = content['token']
"""Discordid = request.form.get("discordid")
token = request.form.get("token")"""
print(Discordid, token)
return ("Thx")
at print(content) I get None I really don't know whts wrong here. I was planning to send Json with information but I getting None from Json.
The very least you're missing is enabling output on the connection. Add:
httpURLConnection.setDoOutput(true);
The server may also require that you set some headers, for example content-type to tell it that you are sending JSON.
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
If you can use Java 11, consider using the new HttpClient class instead of HttpUrlConnection. It simplifies creating correct requests.
NOTICE UPDATE!!
The problem got solved and i added my own answer in the thread
In short, I have attempted to add the parameter "scan_id" value but since it is a POST i can't add the value directly in the url path.
using the code i already have, how would i go about modifying or adding so that the url is correct, that is, so that it accepts my POST?.
somehow i have been unable to find any examples that have helped me in figuring out how i would go about doing this..
I know how to do a POST with a payload, a GET with params. but a post with Params is very confusing to me.
Appreciate any help. (i'd like to continue using HttpUrlConnection unless an other example is provided that also tells me how to send the request and not only configuring the path.
I've tried adding it to the payload.
I've tried UriBuilder but found it confusing and in contrast with the rest of my code, so wanted to ask for help with HttpUrlConnection.
URL url = new URL("http://localhost/scans/{scan_id}/launch");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("tmp_value_dont_mind_this", "432432");
con.setRequestProperty("X-Cookie", "token=" + "43432");
con.setRequestProperty("X-ApiKeys", "accessKey="+"43234;" + " secretKey="+"43234;");
con.setDoInput(true);
con.setDoOutput(true); //NOT NEEDED FOR GETS
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
//First example of writing (works when writing a payload)
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
//second attemp at writing, doens't work (wanted to replace {scan_id} in the url)
DataOutputStream writer = new DataOutputStream(con.getOutputStream());
writer.writeChars("scan_id=42324"); //tried writing directly
//writer.write(payload);
writer.close();
Exception:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost/scans/launch
I'd like one of the three response codes because then i know the Url is correct:
200 Returned if the scan was successfully launched.
403 Returned if the scan is disabled.
404 Returned if the scan does not exist.
I've tried several urls
localhost/scans/launch,
localhost/scans//launch,
localhost/scans/?/launch,
localhost/scans/{scan_id}/launch,
So with the help of a friend and everyone here i solved my problem.
The below code is all the code in an entire class explained bit by bit. at the bottom you have the full class with all its syntax etc, that takes parameters and returns a string.
in a HTTP request there are certain sections.
Such sections include in my case, Request headers, parameters in the Url and a Payload.
depending on the API certain variables required by the API need to go into their respective category.
My ORIGINAL URL looked like this: "http://host:port/scans/{scan_id}/export?{history_id}"
I CHANGED to: "https://host:port/scans/" + scan_Id + "/export?history_id=" + ID;
and the API i am calling required an argument in the payload called "format" with a value.
String payload = "{\"format\" : \"csv\"}";
So with my new URL i opened a connection and set the request headers i needed to set.
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
The setDoOutput should be commented out when making a GET request.
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("X-Cookie", "token=" + token);
con.setRequestProperty("X-ApiKeys", "accessKey="+"23243;" +"secretKey="+"45543;");
Here i write to the payload.
//WRITING THE PAYLOAD to the http call
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
After i've written the payload i read whatever response i get back (this depends on the call, when i do a file download (GET Request) i don't have a response to read as i've already read the response through another piece of code).
I hope this helps anyone who might encounter this thread.
public String requestScan(int scan_Id, String token, String ID) throws MalformedInputException, ProtocolException, IOException {
try {
String endpoint = "https://host:port/scans/" + scan_Id + "/export?history_id=" ID;
URL url = new URL(endpoint);
String payload= "{\"format\" : \"csv\"}";
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("X-Cookie", "token=" + token);
con.setRequestProperty("X-ApiKeys", "accessKey="+"324324;" +
"secretKey="+"43242;");
//WRITING THE PAYLOAD to the http call
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
//READING RESPONSE
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
con.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
As discussed here the solution would be to change the content type to application/x-www-form-urlencoded, but since you are already using application/json; charset=UTF-8 (which I am assuming is a requirement of your project) you have no choise to redesign the whole thing. I suggest you one of the following:
Add another GET service;
Add another POST service with content type application/x-www-form-urlencoded;
Replace this service with one of the above.
Do not specify the content type at all so the client will accept anything. (Don't know if possible in java)
If there are another solutions I'm not aware of, I don't know how much they would be compliant to HTTP protocol.
(More info)
Hope I helped!
Why you are not using like this. Since you need to do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
String urlParameters = "scan_id=42324";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
dataOutputStream.write(postData);
Or if you have launch in the end, just change the above code to the following,
String urlParameters = "42324/launch";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
dataOutputStream.write(postData);
URL url = new URL("http://localhost/scans/{scan_id}/launch");
That line looks odd to me; it seems you are trying to use a URL where you are intending the behavior of a URI Template.
The exact syntax will depend on which template implementation you choose; an implementation using the Spring libraries might look like:
import org.springframework.web.util.UriTemplate;
import java.net.url;
// Warning - UNTESTED code ahead
UriTemplate template = new UriTemplate("http://localhost/scans/{scan_id}/launch");
Map<String,String> uriVariables = Collections.singletonMap("scan_id", "42324");
URI uri = template.expand(uriVariables);
URL url = uri.toURL();
I want to hit a URL in php from java servlet.I just want to send a information to that url.I didn't need to go to that url.i want to stay in my page.Anyway to do that.?
You could simply make a post on that url like in the http components doc
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
Try following code
URL url = new URL("your url");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5000); // time out
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
String postData = "your post data";
out.print(postData);
out.close();
String response connection.getInputStream();
or you can use
Request.Post("your url").bodyForm(
Form.form().add("parameter name", "value")
.add("parameter name1", "value").build()).execute();
String album = "http://picasaweb.google.com/data/feed/api/user/"+email;
HttpURLConnection con = (HttpURLConnection) new URL(albumUrl).openConnection();
// request method, timeout and headers
con.setRequestMethod("GET") ;
con.setReadTimeout(15000);
con.setRequestProperty("Authorization", "GoogleLogin auth="+auth);
con.setRequestProperty("GData-Version", "2");
// set timeout and that we will process output
con.setReadTimeout(15000);
con.setDoOutput(true);
// connnect to url
con.connect();
// read output returned for url
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Problem : Everytime i call con.getInputStream() it gives me file not found exception.
But when i load the same url in the desktop browser then it is displaying correct data.
I am confused why on android it is throwing exception.
Thanks in advance.
Did you get this? Maybe you just missed the https
below example uses default for authenticated user and the experimental fields list.
url = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&access=public&fields="
+ URLEncoder
.encode("entry(title,id,gphoto:numphotosremaining,gphoto:numphotos,media:group/media:thumbnail)",
"UTF-8");
https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#ListAlbums
I want to post among other data a String variable to a PHP file by using the HttpConnection stuff. The first data is the byte[] data returned from a recordstore. So it should be posted alone. So how to post the String variable also ?
You can pass the data to a PHP file using GET or POST methods.
Get method is the easy way to pass simple data. Using GET you can add the variable to the URL
Example:
192.168.1.123/myproject/uploads/treatphoto.php?myVariable1=MyContent&myVariable2=MyContent2
And in PHP:
$content1 = $_GET['myVariable1'];
$content2 = $_GET['myVariable2'];
Also the content of "MyContent" needs to be an string encoded. using any UrlEncoder.
To pass a byte[] array using this method you need to convert the byte array to an string encoded in some printable encoding like base64
The GET method also has a sort limit of data that can be passed safely (usually 2048 bytes)
The other method "POST" is more complex (but not a lot), way to add more data.
You need to prepare the HttpConnection to pass the data as POST.
Also the data stored in urlParamenters need to be according to the url enconding.
Passing the data using post is similar to GET but instead of adding all the variables next to the url the varuiables are added in the Stream of the httpConnection request.
example of the java code:
String urlParameters = "myVariable1=myValue1&myVariable2=myValue2";
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
// Use post and add the type of post data as URLENCODED
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Optinally add the language and the data content
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
// Set the mode as output and disable cache.
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
// Get Response
// Optionally you can get the response of php call.
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
The php is similar, you only need to replace $_GET by $_POST:
$content1 = $_POST['myVariable1'];
$content2 = $_POST['myVariable2'];