Reddy360
Reddy360

Reputation: 11

Upload image from Java to PHP

I've got a webserver setup ready to receive images and I'd like to have a client in Java send the image along with two POST arguments, upon searching the web I only found ways to do this with Apache's API but I'd prefer to do this in vanilla Java.

Any help will be appreciated.

Upvotes: 1

Views: 280

Answers (1)

Matthew Trout
Matthew Trout

Reputation: 741

Something along the lines of...

String url = "https://asite.com";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "aparam=1&anotherparam=2";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

You can add more headers, and add more to the output stream as required.

Upvotes: 4

Related Questions