Java http文件上传和服务器响应

时间:2016-02-04 16:13:40

标签: java httpclient apache-httpclient-4.x

我一直在尝试开发一个桌面java应用程序,它可以将图像从本地硬盘上传到我的网站,并获取一个动态创建的页面的URL,用于该图像。我遇到了可以发送POST请求的HttpClient,但是有很多已弃用的类,我还没有看到除了HTTP状态代码之外如何从服务器获取一些信息。我不熟悉并且非常希望避免的第二种方法是在JAVA中重建服务器端。

哪个是通过上传表单(在PHP中处理)上传文件并将一些信息(如图像的新URL)返回给JAVA应用程序的最简单的解决方案?

1 个答案:

答案 0 :(得分:1)

您可以非常轻松地阅读POST请求的响应(假设您已经在POST中将文件上传到服务器 - 如果没有检出How to upload a file using Java HttpClient library working with PHP,但我在这里复制了关键行):

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);

哦,顺便说一句,这是

 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;