2011-04-14 161 views

回答

3

一个简单的例子了HTTP POST请求在这里给出:

try { 
    // Construct data 
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); 
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8"); 

    // Send data 
    URL url = new URL("http://hostname:80/cgi"); 
    URLConnection conn = url.openConnection(); 
    conn.setDoOutput(true); 
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
    wr.write(data); 
    wr.flush(); 

    // Get the response 
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String line; 
    while ((line = rd.readLine()) != null) { 
     // Process line... 
    } 
    wr.close(); 
    rd.close(); 
} catch (Exception e) { 
} 
11

Android API有一组函数,允许您使用HTTP请求,POST,GET等。 在此示例中,我将提供一组代码,以便您更新服务器中文件的内容使用POST请求。

我们的服务器端代码将非常简单,它将用PHP编写。 该代码将从发布请求中获取数据,使用数据更新文件并加载此文件以在浏览器中显示该文件。

上创建服务器 “mypage.php” PHP页面上,PHP页面的代码是: -

<?php 

$filename="datatest.html"; 
file_put_contents($filename,$_POST["fname"]."<br />",FILE_APPEND); 
file_put_contents($filename,$_POST["fphone"]."<br />",FILE_APPEND); 
file_put_contents($filename,$_POST["femail"]."<br />",FILE_APPEND); 
file_put_contents($filename,$_POST["fcomment"]."<br />",FILE_APPEND); 
$msg=file_get_contents($filename); 
echo $msg; ?> 

创建的Android项目和HTTPExample.java

  HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://example.com/mypage.php"); 
     try { 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); 

     nameValuePairs.add(new BasicNameValuePair("fname", "vinod")); 
     nameValuePairs.add(new BasicNameValuePair("fphone", "1234567890")); 
     nameValuePairs.add(new BasicNameValuePair("femail", "[email protected]")); 
     nameValuePairs.add(new BasicNameValuePair("fcomment", "Help")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 

添加权限下面写代码在AndroidManifest.xml中

<uses-permission android:name="android.permission.INTERNET"/> 
+0

我已经与你的代码做有问题不幸关闭我已完全插入许可证 - 互联网....你可以添加更多的代码....为什么我得到的错误和价值观不会服务器.... – Amitsharma 2014-02-18 10:34:55

相关问题