[英]Java HttpPost to a php API
Im trying to upload a file to a site using their API trough java on android. 我正在尝试使用其在Android上的API的API将文件上传到网站。
This is what im using to post and get a response: 这就是即时通讯用来发布并获得回复的方式:
public static HttpResponse upload(String imagePath){
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.site.com/api.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "file"));
nameValuePairs.add(new BasicNameValuePair("image", "@" + imagePath));
nameValuePairs.add(new BasicNameValuePair("thumbsize", "200"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
System.out.println("tryar");
System.out.println(EntityUtils.toString(httppost.getEntity()));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return response;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The response is a xml file witch i read and that part seems to work. 响应是我读取的一个xml文件,并且该部分似乎起作用。 The response i get is "No file uploaded!".
我得到的答复是“没有文件上传!”。
The site have an example on how to call the api from php curl: 该网站提供了有关如何从php curl调用api的示例:
// post with curl
$ch = curl_init($postURL);
$post['type']='file';
$post['image']='@'.$filename;
// You can set this to either 100,200,300, or 400 to specify the size of the thumbnail
$post['thumbsize']="400";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 240);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
$result = curl_exec($ch);
curl_close($ch);
return $result;
http://www.glowfoto.com/api_upload.php http://www.glowfoto.com/api_upload.php
I have a very limited knowledge of webprogramming but isn't this equivalent to what im doing in java? 我对Web编程的了解非常有限,但这不等于我在Java中做什么吗?
You have to post the file, not just a filename with a @
sign. 您必须发布文件,而不仅仅是带有
@
符号的文件名。 Curl has a form emulation capability which defines that variables starting with @ mean file uploads, but that is strictly a cURL function . Curl具有形式仿真功能,该功能定义以@ mean文件开头的变量,但这严格是cURL函数 。 Do not expect the same behavior from Android API.
不要期望Android API会出现相同的行为。
Yocan use File
and MultipartEntity
. Yocan使用
File
和MultipartEntity
。 This question has a nice example code. 这个问题有一个不错的示例代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.