Reputation: 155
I've been trying to develop a desktop java app which can upload an image from local hard disk to my website and get a URL of a page dynamically created in PHP for that image. I came across HttpClient which can send a POST request, but has a lot of deprecated classes and I haven't seen how to get some information back from server besides HTTP status codes. Second approach which I am not familiar with and would really like to avoid is rebuilding a server side in JAVA.
Which would be the simplest solution for uploading a file via upload form (which is processed in PHP) and getting back some information like new URL of image to the JAVA application?
Upvotes: 2
Views: 2105
Reputation: 1489
you can read the response of the POST request pretty easily (Assuming you have already uploaded the file to the server in a POST - if not check out How to upload a file using Java HttpClient library working with PHP, but i copied the critical lines here):
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
File file = new File("c:/TRASH/zaba_1.jpg");
FileEntity reqEntity = new FileEntity(file, "binary/octet-stream");
reqEntity.setContentType("binary/octet-stream");
post.setEntity(reqEntity);
HttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
Log.d("INFO", "rcode:" + response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() - 200 >= 100)
throw new Exception("bad status code: " + response.getStatusLine().getStatusCode());
String responseString = EntityUtils.toString(entity);
oh btw this is using
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
Upvotes: 3