(2012-11-27 11:23:26)
访问url,需要连接网络。所以,首先应该添加Manifest权限:
<uses-permission android:name="android.permission.INTERNET"/>
1.Get请求(核心代码)
private String baseUrl="http://192.168.1.100:8080/serverside/name"; private String name,age; //代表用户输入的请求内容 private HttpResponse httpResponse; private HttpEntity httpEntity; private InputStream inputStream; public void onClick(View v){ //此处的name+age,作为数据发送 String url=baseUrl+"?"+"name="+name+"&"+"age="+age; //生成一个请求对象 HttpGet httpGet=new HttpGet(url); //生成一个http客户端对象 HttpClient httpClient=new DefaultHttpClient(); //使用客户端发送请求对象 try { //接收服务器返回的响应 httpResponse=httpClient.execute(httpGet); //获取响应的内容 httpEntity=httpResponse.getEntity(); //将内容写入流中 inputStream=httpEntity.getContent(); //InputStreamReader是字节流到字符流的桥梁,将字节流转换为字符流存入缓冲区BufferedReader中 BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String result=""; String line=""; //每次读取一行数据 while((line=bufferedReader.readLine()) != null){ result=result+line; } //输出服务器返回的内容 System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } |
2、POST请求(核心代码)
private String baseUrl="http://192.168.1.100:8080/serverside/name"; private String name,age; private HttpResponse httpResponse; private HttpEntity httpEntity; private InputStream inputStream; public void onClick(View v){ //把请求的数据,添加到NameValuePair中 NameValuePair nameValuePair1=new BasicNameValuePair("name", name); NameValuePair nameValuePair2=new BasicNameValuePair("age", age); //将其添加到list列表中 List list=new ArrayList(); list.add(nameValuePair1); list.add(nameValuePair2); try { //将列表添加到HttpEntity中 HttpEntity requesthttpEntity=new UrlEncodedFormEntity(list); //生成一个请求对象 HttpPost httpPost=new HttpPost(baseUrl); //httpPost设置Entity ==把数据添加到了httpPost中 httpPost.setEntity(requesthttpEntity); //生成一个http客户端对象 HttpClient httpClient=new DefaultHttpClient();
httpResponse=httpClient.execute(httpPost); httpEntity=httpResponse.getEntity(); inputStream=httpEntity.getContent(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String result=""; String line=""; while((line=bufferedReader.readLine()) != null){ result=result+line; } System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } |
3.总结
---Android中,用GET和POST访问http资源--- ·GET请求请提交的数据放置在HTTP请求协议头(也就是url)中,而POST提交的数据则放在实体数据中,安全性比较高。 ·GET方式提交的数据最多只能有1024字节,而POST则没有此限制 两种方法,只是传送数据的方式不同。根据不同的服务器规定的请求访问方式,灵活的运行Get和Post。 |
来源:https://www.cnblogs.com/wenfei123chai/p/4721324.html