手机端与服务端交互类

Android中通过HTTP协议与服务器进行数据交换
package com.suniot.caigou.utils;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.text.TextUtils;

import com.lyh.lib.utils.DebugLog;
import com.suniot.caigou.config.Constants;
import com.suniot.caigou.config.Shared;
import com.suniot.caigou.entity.JsonResult;
import com.suniot.caigou.parser.JsonParser;
import com.suniot.caigou.request.base.RequestParameter;

/**
 * @author lyh
 * @description 手机端与服务端交互类
 * @date 2015-04-03
 */
public class ServerUtils<T> {

	private RequestParameter rp;
	private Class<T> classOfT;
	private Type typeOfT;
	private String ECS_ID = "ECS_ID";

	public ServerUtils(RequestParameter rp, Class<T> classOfT) {
		this.rp = rp;
		this.classOfT = classOfT;
		init();
	}

	public ServerUtils(RequestParameter rp, Type typeOfT) {
		this.rp = rp;
		this.typeOfT = typeOfT;
		init();
	}

	public DefaultHttpClient client;

	/**
	 * 以HttpPost请求服务,并返回需要的格式化信息
	 */
	public JsonResult<T> post() {
		String url = rp.getUrl().concat(UrlUtils.createLinkString(rp.getHttpGetParams()));
		DebugLog.e(url);
		HttpPost post = new HttpPost(url);
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, Constants.SO_TIMEOUT);
		post.setParams(params);
		post.setHeaders(Constants.headers);
		post.setHeader("Cookie", getCookie());
		JsonResult<T> result = null;

		try {
			MultipartEntityBuilder meb = MultipartEntityBuilder.create();

			// 添加数据
			if (rp.getHttpPostParams() != null
					&& rp.getHttpPostParams().size() > 0) {
				for (Map.Entry<String, Object> entry : rp.getHttpPostParams().entrySet()) {
					if (entry.getValue() != null) {
						ContentType type = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), Constants.DEFAULT_CHARSET);
						meb.addTextBody(entry.getKey(), String.valueOf(entry.getValue()), type);
					}
				}
			}

			// 添加文件
			if (rp.getHttpPostFiles() != null
					&& rp.getHttpPostFiles().size() > 0) {
				for (Map.Entry<String, String> entry : rp.getHttpPostFiles().entrySet()) {
					File file = new File(entry.getValue());
					if (file.exists()) {
						meb.addBinaryBody(entry.getKey(), file);
					}
				}
			}

			// 生成 HTTP 实体
			HttpEntity reqEntity = meb.build();
			post.setEntity(reqEntity);

			// 执行 HTTP 请求
			HttpResponse response = client.execute(post);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String json = EntityUtils.toString(response.getEntity(), Constants.DEFAULT_CHARSET);
				DebugLog.e(json);
				if (classOfT != null)
					result = new JsonParser<T>(classOfT).parseJSON(json);
				else if (typeOfT != null)
					result = new JsonParser<T>(typeOfT).parseJSON(json);
			}
		} catch (Exception e) {
			DebugLog.e(e.toString());
		}

		saveCookie();
		return result;
	}

	/**
	 * 以HttpGet请求服务,并返回需要的格式化信息
	 */
	public JsonResult<T> get() {
		String url = rp.getUrl().concat(UrlUtils.createLinkString(rp.getHttpGetParams()));
		DebugLog.e(url);
		HttpGet get = new HttpGet(url);
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, Constants.SO_TIMEOUT);
		get.setParams(params);
		get.setHeaders(Constants.headers);
		get.setHeader("Cookie", getCookie());
		JsonResult<T> result = null;

		try {
			HttpResponse response = client.execute(get);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String json = EntityUtils.toString(response.getEntity(), Constants.DEFAULT_CHARSET);
				DebugLog.e(json);
				if (classOfT != null)
					result = new JsonParser<T>(classOfT).parseJSON(json);
				else if (typeOfT != null)
					result = new JsonParser<T>(typeOfT).parseJSON(json);
			}
		} catch (Exception e) {
			DebugLog.e(e.toString());
		}
		saveCookie();
		return result;
	}

	/**
	 * 保存当前Cookie
	 */
	public void saveCookie() {
		if (client != null)
			CookieUtils.saveCookie(rp.getContext(), client);
	}

	/**
	 * 获得需要发送至服务器的Cookie
	 * 
	 * @return
	 */
	private String getCookie() {
		String cookie = Shared.getCookie(rp.getContext());
		String sid = Shared.getSid(rp.getContext());
		if (!cookie.contains(ECS_ID) && !TextUtils.isEmpty(sid)) {
			cookie += String.format("%s=%s;", ECS_ID, sid);
		}
		return cookie;
	}

	/**
	 * 初始化
	 */
	private void init() {
		client = new DefaultHttpClient();
		if (rp.getHttpGetParams() == null)
			rp.setHttpGetParams(new HashMap<String, Object>());
		if (rp.getHttpPostParams() == null)
			rp.setHttpPostParams(new HashMap<String, Object>());
		rp.getHttpGetParams().put(Constants.SOURCE_NAME, Constants.SOURCE_VALUE);
		rp.getHttpPostParams().put(Constants.SOURCE_NAME, Constants.SOURCE_VALUE);
		rp.getHttpGetParams().put(Constants.OUTPUT_NAME, Constants.OUTPUT_VALUE);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 连接手机端需要通过网络进行通信,而 Spring Boot 提供了多种网络通信方式,例如 HTTP、WebSocket 等。下面以 HTTP 通信为例,介绍 Spring Boot 连接手机端的步骤: 1. 确定手机端和 Spring Boot 服务端所在的网络环境,例如是否在同一局域网内。 2. 在 Spring Boot 中创建一个控制器(Controller),使用 `@RestController` 注解标记,该控制器用于处理 HTTP 请求。 3. 在控制器中编写处理 HTTP 请求的方法,例如使用 `@RequestMapping` 注解标记方法,指定处理的 URL 地址和请求方法型(GET、POST 等)。 4. 在处理请求的方法中,返回需要发送给手机端的数据,例如 JSON 格式的数据。 5. 在手机端使用 HTTP 客户端库(例如 OkHttp)向 Spring Boot 服务端发送 HTTP 请求,获取返回的数据。 需要注意的是,在连接手机端时需要考虑网络安全问题,例如使用 HTTPS 协议进行通信,对数据进行加密等。 ### 回答2: 连接手机端的步骤主要包括以下几个步骤: 1. 搭建服务器:使用Spring Boot框架搭建服务器,可以使用Java语言编写后端代码。Spring Boot提供了简单且高效的方式来创建和发布基于Java的应用程序。 2. 编写接口:在服务器中编写接口,用于手机端与服务器之间的通信。可以使用Spring Boot的Restful API来开发接口,提供数据传输和交互功能。 3. 手机端开发:在手机端开发中,可以使用Android或iOS开发平台进行应用程序的开发。根据服务器接口的需求,编写与服务器进行交互的代码。 4. 连接服务器:在手机端应用程序中,使用网络编程的方式连接服务器。可以使用HTTP协议进行数据传输,通过POST或GET方法与服务器进行交互。 5. 数据传输:在手机端应用程序中,通过网络编程将数据发送给服务器或从服务器获取数据。可以使用JSON或XML等数据格式进行数据的传输和解析。 6. 处理请求:服务器接收到来自手机端的请求后,根据接口中的逻辑处理请求。可以对请求进行验证、数据处理、数据库操作等。 7. 响应手机端:服务器处理完请求后,将处理结果以响应的方式返回给手机端。可以使用JSON或XML等格式将数据返回给手机端。 8. 手机端处理响应:手机端应用程序接收到来自服务器的响应后,进行相关处理。可以解析响应数据,更新UI界面,展示服务器返回的内容。 总结起来,连接手机端的步骤包括搭建服务器、编写接口、手机端开发、连接服务器、数据传输、处理请求、响应手机端手机端处理响应等环节。这些步骤可以通过使用Spring Boot框架、Android或iOS开发平台以及网络编程技术实现。 ### 回答3: Spring Boot 是一个开源的Java开发框架,可以轻松地创建独立的、生产级别的Spring应用。连接手机端步骤如下: 1. 添加相应的依赖:在Spring Boot项目的pom.xml文件中,添加与手机端连接相关的依赖,比如WebSocket依赖或者移动端网络请求库的依赖,可以使用Maven或Gradle自动下载依赖。 2. 编写控制器代码:在Spring Boot项目中,编写与手机端进行通信的控制器代码。可以使用Spring MVC框架,编写相应的请求和响应处理方法。 3. 创建WebSocket连接:如果使用WebSocket与手机端进行实时通信,首先需要在Spring Boot项目中创建WebSocket连接。可以使用Spring框架提供的WebSocket支持,创建一个WebSocket处理器来处理与手机端的连接请求和消息。 4. 编写手机端代码:在手机端,可以使用安卓或iOS开发平台编写相应的代码。根据需求,可以使用WebSocket、HTTP请求或其他协议与Spring Boot应用进行通信。根据具体的功能需求,编写相应的代码以实现与Spring Boot应用的连接和交互。 5. 测试连接:在开发完成后,可以使用手机设备或模拟器来测试与Spring Boot应用的连接。确保手机端能够与应用正常通信,并处理相应的请求和响应。 总结来说,连接手机端步骤包括添加依赖、编写控制器代码、创建WebSocket连接、编写手机端代码和进行连接测试。这样可以实现手机端与Spring Boot应用的连接和通信,实现不同功能的交互
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值