android 客户端数据传递之二:基于Http协议获取数据 代码

来源:互联网 发布:卡夫亨氏的管培生 知乎 编辑:程序博客网 时间:2024/06/12 00:21

http://sizeed.blog.163.com/blog/static/965254512011102145327434/


这里需要注意的是模拟器把自己当成了localhost,以及127.0.0.1了,因此如果基于本地的web项目测试的话,必须修改IP为:10.0.2.2


public class TestPostHtml extends Activity {     /** Called when the activity is first created. */  //模拟器自己把自己当成localhost了,服务器应该为10.0.2.2  private static  String url="http://110.80.10.194:11000/p.php";  @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  getPDAServerData(url);       } /**     * 请求服务     * @param url     */ private void getPDAServerData(String url){  url+="?username=123456";       HttpClient client=new DefaultHttpClient();  HttpPost request;        try {         request = new HttpPost(new URI(url));   HttpResponse response=client.execute(request);   //判断请求是否成功         if(response.getStatusLine().getStatusCode()==200){    HttpEntity  entity=response.getEntity();        if(entity!=null){         //String out=EntityUtils.toString(entity).getBytes("utf-8").toString();     String out=new String(EntityUtils.toString(entity).getBytes("ISO8859-1"),"utf-8");     Log.i("显示数据",""+out);     new AlertDialog.Builder(this).setMessage(out).create().show();         }          }        }catch (URISyntaxException e) {    e.printStackTrace();    Log.i("URISyntaxException",""+e);    }        catch (ClientProtocolException e) {    e.printStackTrace();      Log.i("ClientProtocolException",""+e);   } catch (IOException e) {    e.printStackTrace();     }      } }

原创粉丝点击