2011-04-14 163 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

相關問題