|
在上篇中使用HttpGet获取服务器数据后,本文我们使用HttpPost的方式来提交数据。稍微有一点不同的就是需要使用BasicNameValuePair来放一些Post的数据。
在访问web页面的数据
{“title”:”未输入”,”id”:1,”value”:”7030ff64701a938becbc5aa67ddb86e8″}
—————————————————————————————
先看php代码
- < ?php
- header("Content-Type: text/html; charset=UTF-8");
- if(isset($_POST['username']) && isset($_POST['password']))
- {
- $username = $_POST['username'];
- $password = $_POST['password'];
- if($username == "huzhangyou" && $password == "windows")
- {
- $array = array( 'title'=>urlencode('登陆成功'), 'id'=>1, 'value'=>md5(md5($username. $password)));
- echo urldecode(json_encode($array));
- }
- else
- {
- $array = array( 'title'=>urlencode('登录失败'), 'id'=>1, 'value'=>md5("错误"));
- echo urldecode(json_encode($array));
- }
- }
- else
- {
- $array = array( 'title'=>urlencode('未输入'), 'id'=>1, 'value'=>md5("错误"));
- echo urldecode(json_encode($array));
- }
- ?>
复制代码 —————————————————————————————
java部分核心代码:
- public void postServerJsonDataWithNoType(String url,EditText editText)
- {
- HttpPost httpPost = new HttpPost(url);
- HttpClient client = new DefaultHttpClient();
- StringBuilder str = new StringBuilder();
- ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("username","huzhangyou"));
- params.add(new BasicNameValuePair("password","windows"));
- BufferedReader buffer = null;
- try
- {
- httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- HttpResponse httpRes = client.execute(httpPost);
- if(httpRes.getStatusLine().getStatusCode() == 200)
- {
- buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
- for(String s = buffer.readLine(); s != null ; s = buffer.readLine())
- {
- str.append(s);
- }
- //String out = EntityUtils.toString(httpRes.getEntity().getContent(), "UTF-8");
- //StringBuilder sb = new StringBuilder()
- Log.i(Tag,str.toString());
- buffer.close();
- JSONObject json = new JSONObject(str.toString());
- String title = json.getString("title");
- Log.i(Tag,title);
- int id = json.getInt("id");
- String value = json.getString("value");
- Log.i(Tag,value);
- editText.setText("Title:" + title + " ID:" + id + " Value:" + value);
- }
- }
- catch(Exception e)
- {
- if(buffer != null)
- {
- try {
- buffer.close();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- }
- }
- }
复制代码 —————————————————————————————
项目代码下载:
php:
phpjson
java代码:
PHPJson
1 http://blog.csdn.net/firewings_r/article/details/5374851
2 http://www.ineeke.com/archives/1317/
3 http://lrc-1986.iteye.com/blog/868799
4 http://stackoverflow.com/questio ... w-to-get-the-result
5 http://stackoverflow.com/questio ... ttp-post-in-android
6 http://www.anddev.org/doing_http_post_with_android-t492.html
|
|