Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HttpPost到php API_Java_Android - Fatal编程技术网

Java HttpPost到php API

Java HttpPost到php API,java,android,Java,Android,我正试图通过android上的java将一个文件上传到一个使用API的站点 这是我用来发布和获得回复的工具: public static HttpResponse upload(String imagePath){ // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("

我正试图通过android上的java将一个文件上传到一个使用API的站点

这是我用来发布和获得回复的工具:

    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;

}


我对网络编程的了解非常有限,但这不等于我在java中所做的吗?

你必须发布文件,而不仅仅是带有
@
符号的文件名。Curl具有定义以@mean file uploads开头的变量的功能,但严格来说,这是一个Curl函数。不要期望Android 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;