Android通过网址发布数据

时间:2013-10-09 16:15:11

标签: android web-services url androidhttpclient

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

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

有人可以指导我,告诉我该怎么做。

2 个答案:

答案 0 :(得分: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权限

希望这有帮助!

答案 1 :(得分:0)

使用HTTP client课程,并通过特定的URI constructor.格式化您的网址HTTP post,可选择设置实体,标题等,通过客户端执行帖子,接收HTTP response,将entity从响应中拉出来并进行处理。

EDIT例如:

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.