【问题标题】:HTTP Post request AndroidHTTP Post 请求 Android
【发布时间】:2012-07-10 10:47:30
【问题描述】:

我正在尝试从 Android 联系 API

我找到了这个示例代码...

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

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

我的问题是,我如何查看回复以确保收到回复?有没有办法添加 API 密钥?

另外,“yoursite.com”是否必须是 PHP 文件?

【问题讨论】:

  • 服务器不必在 php 中使用任何你想要的服务器端。我们使用 python 和 Django。

标签: java php android api http-post


【解决方案1】:
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();
    try {

        //read stream 
        //if expect binary data:
        BufferedInputStream stream = new BufferedInputStream(instream);
        int maxBytes = 128 * 1024;
        if(entity.getContentLength() > maxBytes) {
            throw new IllegalArgumentException("Much too big!");
        }
        byte[] bytes = new byte[(int) entity.getContentLength()];
        int offset = 0, count = bytes.length;
        while(stream.read(bytes, offset, count) > -1 && count > 0) {
            count -= offset;
        }

        final Bitmap responseImage = BitmapFactory.decodeByteArray(
                bytes, 0, bytes.length);

        //or if you expect text
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(instream, Charset.forName(
                        entity.getContentEncoding().getValue())));

        StringBuffer buffer = new StringBuffer();
        String line;
        while((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        final String responseText = buffer.toString();

    } finally {
        instream.close();
    }
}

【讨论】:

    【解决方案2】:

    观看这些视频(YouTube Link)

    这是一个 6 部分的教程,用于制作安卓登录应用程序。 它还展示了如何使用 MySQL 创建数据库。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 2015-03-08
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      相关资源
      最近更新 更多