【问题标题】:Get data from an internet link in Android从 Android 中的 Internet 链接获取数据
【发布时间】:2011-06-07 07:23:33
【问题描述】:

我正在制作一个带有 URL 的应用程序。 *.asp 扩展名,我们将所需的参数传递给它,并使用 POST 方法获取一些字符串结果。

关于如何实现这一点的任何建议?

更新:

实际上我有一个 .net 链接,它接受一些 POST 参数并给我一个结果。如何在 Android 中做到这一点?

【问题讨论】:

  • 这个网址在哪里加载?你到底在做什么,你到底想实现什么?

标签: android hyperlink http-post


【解决方案1】:

HTTPResponse 应该可以解决问题:

DefaultHttpClient  httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoururl.com");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); <!-- number should be the amount of parameters
nameValuePairs.add(new BasicNameValuePair("nameOfParameter", "parameter"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();

BufferedHttpEntity buf = new BufferedHttpEntity(ht);

InputStream is = buf.getContent();

现在您可以使用流,将数据写入字符串:

BufferedReader r = new BufferedReader(new InputStreamReader(is));

total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
     total.append(line);
}

祝你好运!

【讨论】:

  • 我们如何用它传递参数???它将为此做一些事情并返回结果??
【解决方案2】:

尝试使用 AsynTask (http://developer.android.com/reference/android/os/AsyncTask.html),切勿尝试在 onCreate 调用或任何其他 GUI 线程方法中执行任何耗时的任务。

【讨论】:

    【解决方案3】:

    以下是执行 POST 请求(包括参数)并在 Android 通知中显示收到的响应的 Android 活动的代码:

    package org.anddev.android.webstuff;
    
    import java.io.ByteArrayInputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    import org.apache.http.util.ByteArrayBuffer;
    
    import android.app.Activity;
    import android.app.NotificationManager;
    import android.net.http.EventHandler;
    import android.net.http.Headers;
    import android.net.http.RequestQueue;
    import android.net.http.SslCertificate;
    import android.os.Bundle;
    import android.util.Log;
    
    public class HTTPPostExample extends Activity {
    
            // ===========================================================
            // Fields
            // ===========================================================
    
            private final String DEBUG_TAG = "httpPostExample";
    
            // ===========================================================
            // 'Constructors'
            // ===========================================================
    
            @Override
            public void onCreate(Bundle icicle) {
                    super.onCreate(icicle);
    
                    /* Create a new HTTP-RequestQueue. */
                    android.net.http.RequestQueue rQueue = new RequestQueue(this);
    
                    /* Prepare the Post-Text we are going to send. */
                    String POSTText = null;
                    try {
                            POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                            return;
                    }
                    /* And put the encoded bytes into an BAIS,
                     * where a function later can read bytes from. */
                    byte[] POSTbytes = POSTText.getBytes();
                    ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
    
                    /* Create a header-hashmap */
                    Map<String, String> headers = new HashMap<String, String>();
                    /* and put the Default-Encoding for html-forms to it. */
                    headers.put("Content-Type", "application/x-www-form-urlencoded");
    
                    /* Create a new EventHandler defined above, to handle what gets returned. */
                    MyEventHandler myEvH = new MyEventHandler(this);
    
                    /* Now we call a php-file I prepared. It is exactly this:
                     * <?php
                     *              echo "POSTed data: '".$_POST['data']."'";
                     * ?>*/
                    rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
                                    headers, myEvH, baos, POSTbytes.length,false);
    
                    /* Wait until the request is complete.*/
                    rQueue.waitUntilComplete();
            }
    
            // ===========================================================
            // Worker Class
            // ===========================================================
    
            private class MyEventHandler implements EventHandler {
                    private static final int RANDOM_ID = 0x1337;
    
                    /** Will hold the data returned by the URLCall. */
                    ByteArrayBuffer baf = new ByteArrayBuffer(20);
    
                    /** Needed, as we want to show the results as Notifications. */
                    private Activity myActivity;
    
                    MyEventHandler(Activity activity) {
                            this.myActivity = activity;  }
    
                    public void data(byte[] bytes, int len) {
                            baf.append(bytes, 0, len);  }
    
                    public void endData() {
                            String text = new String(baf.toByteArray());
                            myShowNotificationAndLog("Data loaded: n" + text);  }
    
                    public void status(int arg0, int arg1, int arg2, String s) {
                            myShowNotificationAndLog("status [" + s + "]");  }
    
                    public void error(int i, String s) {
                            this.myShowNotificationAndLog("error [" + s + "]");  }
    
                    public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
                    public void headers(Iterator arg0) { }
                    public void headers(Headers arg0) { }
    
                    private void myShowNotificationAndLog(String msg) {
                            /* Print msg to LogCat and show Notification. */
                            Log.d(DEBUG_TAG, msg);
                            NotificationManager nm = (NotificationManager) this.myActivity
                                            .getSystemService(Activity.NOTIFICATION_SERVICE);
                            nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);
                    }
            }
    }
    

    plusminus的代码

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2015-06-06
      • 2014-08-17
      • 2016-09-10
      • 2018-07-02
      相关资源
      最近更新 更多