gpt4 book ai didi

java - Android 中的 HTTP 获取和发布

转载 作者:行者123 更新时间:2023-12-02 05:56:45 24 4
gpt4 key购买 nike

在我的程序中,我有 http get 从 PHP 脚本获取数据。此代码存在于异步任务中。这工作得很好。

但是现在我想做 HTTP post,我,android 客户端,将数据发送到 PHP 脚本,它查询数据库并返回结果。

但这就是让我困惑的地方。

  1. 我可以从 HTTP post 获得响应吗?或者我需要结合使用 post 和 get 吗?

  2. 这个问题我不希望得到答案,但如果有人能就此提出建议那就太好了。我有一个执行 HTTP 获取的异步任务。现在我想使用相同的异步来执行 HTTP get 或 post,但不能同时执行两者。这可能吗?

谢谢

这里是约翰。一个小 fragment 。我的问题是 HTTP StatusLine httpStatus 和 http 实体,它无法识别任何响应,因为它们位于 if 语句中,因此编译器认为它们不会被定义。

            if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
HttpResponse r = client.execute(get);
}

else //we are posting
{
HttpPost post = new HttpPost(params[0]);
HttpResponse r = client.execute(post);
}

StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();

最佳答案

  1. 您可以通过帖子获得回复
  2. 只要您有一些逻辑可以根据您想要执行的操作将请求类型更改为 POST 或 GET,您就可以使用相同的异步方法。

some info on HttpPost

// 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
}

为了让您的代码正常工作,您需要在 if/blocks 之外声明响应:

        HttpResponse r = null;

if(params[1] == "GETRESULT")
{
HttpGet get = new HttpGet(params[0]);
r = client.execute(get);
}

else //we are posting
{
HttpPost post = new HttpPost(params[0]);
r = client.execute(post);
}

StatusLine httpStatus = r.getStatusLine();
HttpEntity e = r.getEntity();

关于java - Android 中的 HTTP 获取和发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com