Android向服务器传送和接收数据的方法汇总
来源:互联网 发布:iphone当前网络不可用 编辑:程序博客网 时间:2024/05/16 20:10
今天通过收集资料和自己尝试的使用,整理了Android向服务器发送数据的方法主要有以下几种,下面写在一个类中,相应的调用就可实现!
注意:开始我在使用时,调用各种方法总是报错,后来到处查找,但是就是找不到错误,最终在高手的指点下找到了原因,在网络编程时,调用各种方法时,我们一定要在线程完成。
源码:
package com.example.shezhi;import java.io.IOException;import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map; import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URLEncodedUtils;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils; public class Update { String res=" ";int ites;String version="1";///////////////////////////////////////////////////////////////////////////////////////// public String getupdate(){ //先将参数放入List,再对参数进行URL编码 List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); params.add(new BasicNameValuePair("param1", "1")); params.add(new BasicNameValuePair("param2", "value2")); //对参数编码 String param = URLEncodedUtils.format(params, "UTF-8"); //baseUrl String baseUrl = "http://******/index1.jsp"; //将URL与参数拼接 HttpGet getMethod = new HttpGet(baseUrl + "?" + param); HttpClient httpClient = new DefaultHttpClient(); try {HttpResponse response = httpClient.execute(getMethod); res="已经请求";} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} //发起GET请求 try { HttpResponse response = httpClient.execute(getMethod); //发起GET请求 ites=response.getStatusLine().getStatusCode(); //获取响应码 System.out.println(ites+"aaa"); res="1213"+EntityUtils.toString(response.getEntity(), "utf-8");//获取服务器响应内容 System.out.println(res+"vvv"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } /******************************************************************************************** /** * HttpClient Post方法 * @return */ public String Postupdate(){ String urlPath="http://******/index1.jsp"; String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉 HttpPost httpRequest=new HttpPost(realPath); // 添加要传递的参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); NameValuePair pair1 = new BasicNameValuePair("username", "gzw"); NameValuePair pair2 = new BasicNameValuePair("password", "123"); params.add(pair1); params.add(pair2); try { // 设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8"); // 请求httpRequest httpRequest.setEntity(httpentity); // 取得默认的HttpClient HttpClient httpclient = new DefaultHttpClient(); // 取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // HttpStatus.SC_OK表示连接成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 取得返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); res=strResult; } else { res="失败"; } }catch (Exception e) { e.printStackTrace(); } return res; }/********************************************************************************************/ /** * 调用java类 get方法 */ public String get_update(){ String urlPath="http://******/index1.jsp"+"?type=save&version="+version+""; String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉 try { if(getRequest(realPath)) { //成功 res="成功"; } }catch (Exception e) { res="失败"; } return res; } /** * java类 get方法 * @return *///get请求,有文件长度大小限制 public static boolean getRequest(String urlPath) throws Exception { URL url=new URL(urlPath); HttpURLConnection con=(HttpURLConnection)url.openConnection(); con.setRequestMethod("GET"); con.setReadTimeout(5*1000); if(con.getResponseCode()==200) { return true; } return false; } /******************************************************************************************** /** * 调用下面java类 Post方法 * @return */ public String post_update(){ String urlPath="http://www.gdhdcy.com/hdleague1/index1.jsp"; Map<String,String> map=new HashMap<String,String>();//用集合来做,比字符串拼接来得直观 map.put("type", "save"); map.put("version", version); try { if(postRequest(urlPath,map)) { //成功 res="成功"; } }catch (Exception e) { res="失败"; } return res; } /** * java类 post方法 * @return */ //post请求,无文件长度大小限制 public static boolean postRequest(String urlPath,Map<String,String> map) throws Exception { StringBuilder builder=new StringBuilder(); //拼接字符 //拿出键值 if(map!=null && !map.isEmpty()) { for(Map.Entry<String, String> param:map.entrySet()) { builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&'); } builder.deleteCharAt(builder.length()-1); } //下面的Content-Length: 是这个URL的二进制数据长度 byte b[]=builder.toString().getBytes(); URL url=new URL(urlPath); HttpURLConnection con=(HttpURLConnection)url.openConnection(); con.setRequestMethod("POST"); con.setReadTimeout(5*1000); con.setDoOutput(true);//打开向外输出 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//内容类型 con.setRequestProperty("Content-Length",String.valueOf(b.length));//长度 OutputStream outStream=con.getOutputStream(); outStream.write(b);//写入数据 outStream.flush();//刷新内存 outStream.close(); //状态码是不成功 if(con.getResponseCode()==200) { return true; } return false; } }
0 0
- Android向服务器传送和接收数据的方法汇总
- Android向服务器传接和接收数据的方法汇总
- android中通过GET方法接收数据并通过xml解析数据,POST方法向服务器提交数据
- android接收从其他App传送来的数据
- android 接收从其他App传送来的数据
- 通过nsurlsession向服务器传送json数据
- 模拟浏览器向服务器发送和接收数据
- Android向node.js编写的服务器发送数据,并接收请求
- android中用GET和POST的方法向服务器上传数据
- Android--向服务器提交数据的两种方法Post和Get
- android中用GET和POST的方法向服务器上传数据
- Windows DBus如何传送和接收数据
- DBus如何传送和接收数据
- 两种HTTP方法服务器传送表单数据:GET和POST的区别
- android平台通过socket向C++服务器端发送数据和接收数据的相关问题
- android平台通过socket向C++服务器端发送数据和接收数据的相关问题
- android用socket向服务器发送和接收消息 【转自网易闯京城的博客】
- Flex接收服务器端传送的XML数据
- visual studio对于未赋值的int型的处理
- 图像分割___图像分割方法综述
- 【java 大数】hdu java 大数
- 程序员/设计师能用上的 75 份速查表
- CreateThread()与beginthread()的区别详细解析
- Android向服务器传送和接收数据的方法汇总
- 线程
- S3C2440 用按键控制LED
- 第六周工作总结
- Hadoop 在关机重启后,namenode启动报错
- c++笔试----What will print out?
- 第六周工作计划表
- JAVA责任链模式-过滤器原理
- webview的基本使用