简体   繁体   English

如何从Android向Web服务器发送数据

[英]How to send a data to a web server from Android

I want to send data to my php page using android. 我想用android将数据发送到我的php页面。 How can I do it? 我该怎么做?

The Android API has a set of functions that allows you to use HTTP requests, POST, GET etc. In this example i will provide a set of code that will allow you to update the contents of a file in a server using POST requests. Android API有一组函数,允许您使用HTTP请求,POST,GET等。在这个例子中,我将提供一组代码,允许您使用POST请求更新服务器中文件的内容。

Our server side code will be very simple and it will be written in PHP. 我们的服务器端代码非常简单,它将用PHP编写。 The code will get data from a post request, update a file with the data and load this file to display it in a browser. 代码将从post请求中获取数据,使用数据更新文件并加载此文件以在浏览器中显示它。

Create PHP page on server "mypage.php", the code for php page is:- 在服务器“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; ?>

Create Android Project and write below code in HTTPExample.java 创建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", "abc@gmail.com"));
       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
     }

Add permission in AndroidManifest.xml 在AndroidManifest.xml中添加权限

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

You can make GET or POST requests using AndroidHttpClient : 您可以使用AndroidHttpClient发出GET或POST请求:

  1. Create an AndroidHttpClient to execute your requests. 创建一个AndroidHttpClient来执行您的请求。
  2. Create either an HttpGet or HttpPost request. 创建HttpGetHttpPost请求。
  3. Use setEntity and setHeader methods to populate the request. 使用setEntitysetHeader方法填充请求。
  4. Use one of the execute methods on your client with your request. 根据您的请求,在您的客户端上使用其中一种执行方法。

This answer seems like a fairly complete code sample. 这个答案似乎是一个相当完整的代码示例。

A quick example for a HTTP POST request is given here: 这里给出了一个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) {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM