android中的网络协议的运用(make一下一些固定代码)

Soap协议
public static Doctor doctorLogin(String loginName, String password, String terminal) throws AppException {
		Doctor user = null;
		String methodName = "doctorLogin";
		try {
			// 创建soap对象
			SoapObject soapObject = new SoapObject(Constant.loginNamespace, methodName);
			// 添加参数
			soapObject.addProperty("arg0", loginName);
			soapObject.addProperty("arg1", password);
			soapObject.addProperty("arg2", terminal);

			// 设置连接参数
			HttpTransportSE hse = new HttpTransportSE(Constant.loginUrl, Constant.OverTime);
			hse.debug = true;
			SoapSerializationEnvelope sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			sse.bodyOut = soapObject;
			sse.dotNet = false;
			hse.call(null, sse);
			String result = sse.getResponse().toString();

			// 解析结果
			JSONObject jsonObject = new JSONObject(result);
			Boolean resultTag = jsonObject.getBoolean("resultTag");
			if (resultTag) {
				// 使用Gson 实现对Json字符的解析
				String userinfo = jsonObject.getString("doctor");
				GsonBuilder builder = new GsonBuilder();
				Gson gson = builder.create();
				user = gson.fromJson(userinfo, Doctor.class);

			} else {
				String exMsg = jsonObject.getString("msg");
				loginException = exMsg;
				AppException mAppException = new AppException(exMsg);
				throw mAppException;
			}
		} catch (Exception e) {
			AppException mAppException = new AppException(e);
			throw mAppException;
		}
		return user;
	}
http 协议与服务器通信
public List<DoctorAdvice> getDoctoradviceList(String persionID,String beginTime,String endTime) throws Exception {
		List<DoctorAdvice> list = null;
		StringBuffer mBuffer = new StringBuffer();
		mBuffer.append(persionID);
		mBuffer.append("/");
		mBuffer.append(beginTime.replace(" ", "%20"));
		if(D)Log.d(TAG,"beginTime"+ beginTime);
		mBuffer.append("/");
		mBuffer.append(endTime.replace(" ", "%20"));
		if(D)Log.d(TAG, "endTime"+ endTime);
		HttpGet requstGet = new HttpGet(Constant.getDoctoradvicAddress+mBuffer.toString());
		requstGet.setHeader("Accept", "application/json");
		requstGet.setHeader("Content-type", "application/json;charset=UTF-8");
		HttpResponse mResponse = new DefaultHttpClient().execute(requstGet);
		//获取网络连接状态
		int intId = mResponse.getStatusLine().getStatusCode();
		String responsStr = null;
		HttpEntity mEntity = mResponse.getEntity();
		if (mEntity != null) {
			InputStream mInputStream = mEntity.getContent();
			responsStr = StrUtil.convertStreamToString(mInputStream);
			if (D) Log.d(TAG, "医生建议查询:" + responsStr);
			if (intId == 200) {
				GsonBuilder gsonb = new GsonBuilder();
				Gson gson = gsonb.create();
				list = gson.fromJson(responsStr, new TypeToken<ArrayList<DoctorAdvice>>(){}.getType());
			}else{
				GsonBuilder gsonb = new GsonBuilder();
				Gson gson = gsonb.create();
				Fault f = gson.fromJson(responsStr, Fault.class);
				throw new AppException(f.message);
			}
		}
		
		return list;
	}

HTTP协议请求方法:

请求行中包括了请求方法,解释如下:

GET 请求获取Request-URI 所标识的资源;

POST 在Request-URI 所标识的资源后附加新的数据;

HEAD 请求获取由Request-URI 所标识的资源的响应消息报头

PUT 请求服务器存储一个资源,并用Request-URI 作为其标识

DELETE 请求服务器删除Request-URI 所标识的资源;

TRACE 请求服务器回送收到的请求信息,主要用于测试或诊断

CONNECT 保留将来使用

OPTIONS 请求查询服务器的性能,或者查询与资源相关的选项和需求

Get与Post请求区别:

Post请求可以向服务器传送数据,而且数据放在HTML HEADER内一起传送到服务端URL地址,数据对用户不可见。而get是把参数数据队列加到提交的URL中,值和表单内各个字段一一对应, 例如(http://www.baidu.com/s?w=%C4&inputT=2710)

get 传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。

get安全性非常低,post安全性较高。

 

 

get方式:

          get机制用的是在URL地址里面通过?号间隔,然后以name=value的形式给客户端传递参数。所以首先要在Android工程下的AndroidGetTest.java中onCreate方法定义好其URL地址以及要传递的参数,然后通过URL打开一个HttpURLConnection链接,此链接可以获得InputStream字节流对象,也是往服务端输出和从服务端返回数据的重要过程,而若服务端response.getInputStream.write()往andorid返回信息时候,就可以通过InputStreamReader作转换,将返回来的数据用BufferReader显示出来。

具体代码如下:

public class HttpUtils {
    private static String URL_PATH = "http://192.168.1.106:8080/green.jpg";
    /**
     * @param args
     */
    public static void main(String[] args) {
        // 调用方法获取图片并保存
        saveImageToDisk();
    }
    /**
     * 通过URL_PATH的地址访问图片并保存到本地
     */
    public static void saveImageToDisk()
    {
        InputStream inputStream= getInputStream();
        byte[] data=new byte[1024];
        int len=0;
        FileOutputStream fileOutputStream=null;
        try {
            //把图片文件保存在本地F盘下
            fileOutputStream=new FileOutputStream("F:\\test.png");
            while((len=inputStream.read(data))!=-1) 
            {
                //向本地文件中写入图片流
                fileOutputStream.write(data,0,len);                
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            //最后关闭流
            if(inputStream!=null)
            {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null)
            {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 通过URL获取图片
     * @return URL地址图片的输入流。
     */
    public static InputStream getInputStream() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {
            //根据URL地址实例化一个URL对象,用于创建HttpURLConnection对象。
            URL url = new URL(URL_PATH);

            if (url != null) {
                //openConnection获得当前URL的连接
                httpURLConnection = (HttpURLConnection) url.openConnection();
                //设置3秒的响应超时
                httpURLConnection.setConnectTimeout(3000);
                //设置允许输入
                httpURLConnection.setDoInput(true);
                //设置为GET方式请求数据
                httpURLConnection.setRequestMethod("GET");
                //获取连接响应码,200为成功,如果为其他,均表示有问题
                int responseCode=httpURLConnection.getResponseCode();
                if(responseCode==200)
                {
                    //getInputStream获取服务端返回的数据流。
                    inputStream=httpURLConnection.getInputStream();
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

}

post方式
private void httpUrlConnection(){
    try{
     String pathUrl = "http://172.20.0.206:8082/TestServelt/login.do";
     //建立连接
     URL url=new URL(pathUrl);
     HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
     
     设置连接属性
     httpConn.setDoOutput(true);//使用 URL 连接进行输出
     httpConn.setDoInput(true);//使用 URL 连接进行输入
     httpConn.setUseCaches(false);//忽略缓存
     httpConn.setRequestMethod("POST");//设置URL请求方法
     String requestString = "客服端要以以流方式发送到服务端的数据...";
     
     //设置请求属性
    //获得数据字节数据,请求数据流的编码,必须和下面服务器端处理请求流的编码一致
          byte[] requestStringBytes = requestString.getBytes(ENCODING_UTF_8);
          httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
          httpConn.setRequestProperty("Content-Type", "application/octet-stream");
          httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
          httpConn.setRequestProperty("Charset", "UTF-8");
          //
          String name=URLEncoder.encode("黄武艺","utf-8");
          httpConn.setRequestProperty("NAME", name);
          
          //建立输出流,并写入数据
          OutputStream outputStream = httpConn.getOutputStream();
          outputStream.write(requestStringBytes);
          outputStream.close();
         //获得响应状态
          int responseCode = httpConn.getResponseCode();
          if(HttpURLConnection.HTTP_OK == responseCode){//连接成功
           
           //当正确响应时处理数据
           StringBuffer sb = new StringBuffer();
              String readLine;
              BufferedReader responseReader;
             //处理响应流,必须与服务器响应流输出的编码一致
              responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), ENCODING_UTF_8));
              while ((readLine = responseReader.readLine()) != null) {
               sb.append(readLine).append("\n");
              }
              responseReader.close();
              tv.setText(sb.toString());
          }
    }catch(Exception ex){
     ex.printStackTrace();
    }
   }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值