0

在我的应用程序中,我需要将数据发布到 url 以注册新用户。这是网址

http://myurl.com/user.php? email=[EMAIL]&username=[USERNAME]&password[PASS]&img_url=[IMG]

如果我这样做正确,我应该收到以下消息:

{"success":true,"error":null} 
or if not {"success":false,"error":"parameters"}

有人可以指导我完成这个并告诉我该怎么做。

4

2 回答 2

3

首先:
您需要使用以下方法在异步线程中执行所有网络任务:

public class PostData extends AsyncTask<String, Void, String>{
{
        @Override
    protected String doInBackground(String... params) {
    //put all your network code here
}

第二:
创建你的 http 请求:我在这里假设电子邮件、用户名和 IMG 作为变量。

    String server ="http://myurl.com/user.php? email=[" + EMAIL + "]&username=[" + USERNAME + "]&password[" + PASS + "]&img_url=["+IMG + "]";

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(server);

            //httppost.setHeader("Accept", "application/json");
            httppost.setHeader("Accept", "application/x-www-form-urlencoded");
            //httppost.setHeader("Content-type", "application/json");
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

third:     
// Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("JSONdata", Object));     
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

            try {
                HttpResponse response =httpclient.execute(httppost);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

现在简单地查询您的响应处理程序,即在这种情况下的响应。

不要忘记在您的 androidManifest.xml 中添加 INTERNET 权限

希望这可以帮助!

于 2013-10-09T16:52:30.837 回答
0

使用HTTP 客户端类,并通过特定的URI 构造函数格式化您的 URL。创建一个HTTP 帖子,可选地设置实体、标题等,通过客户端执行帖子,接收HTTP 响应,将实体从响应中拉出并处理它。

编辑例如:

HttpClient httpclient = new DefaultHttpClient();
URI uri = new URI("http",  
        "www.google.com",  // connecting to  IP
        "subpath", // and the "path" of what we want
        "a=5&b=6", // query 
        null); // no fragment
HttpPost httppost = new HttpPost(uri.toASCIIString);
// have a body ?
// post.setEntity(new StringEntity(JSONObj.toString()));
// post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
Reader r = new  InputStreamReader(entity.getContent());
// Do something with the data in the reader.
于 2013-10-09T16:23:36.630 回答