Reputation: 2349
I'm trying to get HttpURLConnection
to post a JSON string to a PHP file remotely. It's not working no matter what I do. This is my current code:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL('http://domain.com/me.php').openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
String initial = "{'out': '" + idir + prod + ".jpg', 'in': '" + item[3] + "'}";
byte[] outputBytes = initial.getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);
os.close();
I know that the initial
string contains data, I have run a System.out.println
on it and the outputBytes
variables and both have contents.
I know it's not posting because I have the PHP file set to save posted contents to a file locally. No file is ever created when running it.
I know the PHP side of things work and the server accepts posts as I can run this just fine:
$ curl -H "Accept: application/json" -H "Content-Type: application/json" -d "{'value': 7.5}" "http://domain.com/me.php"
And it works fine creating the file and writing post content to output file.
EDIT
Ok, after printing the responses I'm now getting a 401 code, unauthorized. I'm using Apache HTPASSWD authentication, but I was passing the user and pass in the URL as http://user:[email protected]/me.php
. This worked from curl from the CLI, so I thought it would work here also, evidently it does not.
So how do I authenticate using HttpURLConnection?
Upvotes: 0
Views: 785
Reputation: 1420
You need to set up basic authentication. You can do it through plain Java or using Apache HttpClient.
How to handle HTTP authentication using HttpURLConnection?
http://www.baeldung.com/httpclient-4-basic-authentication
Upvotes: 1