socket http

景信瑞
2023-12-01
package ServerInteract;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.R.integer;
import commontool.*;

public class SocketInteractServer {
	private static final String TAG = "SocketInteractServer";
	
	private int PORT = 7070;
	private String IP = "109.105.3.230";
	private Socket socket = null;
	private DataInputStream in = null;
	private DataOutputStream out = null;

	public boolean isConnected() {
		return socket.isConnected();
	}

	public  SocketInteractServer() {
		IP=Controller.getServerIP();
		PORT=Controller.getServerPort();
		connect();
	}
/**
 * 从SOCKET中读取数据
 * @return
 */
	public String readStr() {
		if (false == isReadable())
			connect();// 重新连接
		String messageString = null;
		byte[] reply = new byte[1024];
		int len = -1;
		try {
			len = in.read(reply);
		} catch (IOException e) {
			CommonFunctions.generateLogV(TAG, "len=in.read(reply);",
					"IOException");
			e.printStackTrace();
		}
		if (len <= 0)
			return null;
		try {
			messageString = new String(reply, "GBK").trim();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			CommonFunctions.generateLogV(TAG, "new String(reply, GBK).trim()",
					"UnsupportedEncodingException");
			e.printStackTrace();
		}
		return messageString;
	}
	/**
	 * 向SOCKET中写入数据
	 * @return
	 */
	public boolean writeStr(String message) {
		 if(false==isWriteable())
		    connect();//重新连接
		byte[] request = message.getBytes();
		try {
			out.write(request);
			out.flush();
		} catch (IOException e) {
			CommonFunctions.generateLogV(TAG, "out.write(request);",
					"IOException");
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean isReadable() {
		return isConnected() && in != null;
	}

	public boolean isWriteable() {
		return isConnected() && out != null;
	}

	public void connect() {
		try {
			socket = new Socket(IP, PORT);
		} catch (UnknownHostException e) {
			CommonFunctions.generateLogV(TAG, "socket=new Socket(IP,PORT)",
					"UnknownHostException");
			e.printStackTrace();
		} catch (IOException e) {
			CommonFunctions.generateLogV(TAG, "socket=new Socket(IP,PORT)",
					"IOException");
			e.printStackTrace();
		}
		try {
			in = new DataInputStream(socket.getInputStream());
		} catch (IOException e) {
			CommonFunctions.generateLogV(TAG,
					"bufferedReader=new BufferedReader...", "IOException");
			e.printStackTrace();
		}
		try {
			out = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			CommonFunctions.generateLogV(TAG,
					"ufferedWriter=new BufferedWriter...", "IOException");
			e.printStackTrace();
		}
	}

	public void close() {
		if (in != null)
			try {
				in.close();
			} catch (IOException e) {
				CommonFunctions.generateLogV(TAG, "n.close();", "IOException");
				e.printStackTrace();
			}
		if (out != null)
			try {
				out.close();
			} catch (IOException e) {
				CommonFunctions.generateLogV(TAG, "out.close()", "IOException");
				e.printStackTrace();
			}
		if (socket != null)
			try {
				socket.close();
			} catch (IOException e) {
				CommonFunctions.generateLogV(TAG, "socket.close()",
						"IOException");
				e.printStackTrace();
			}
	}

}


 

package ServerInteract;

import java.io.IOException;

import android.app.Application;
import android.content.Context;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import commontool.Constants;
import commontool.MyApplication;
import commontool.PreferenceService;

import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;

import MyClasses.RequestServer;
/**
 * HTTP请求服务器
 * @author lz
 *
 */
public class HttpRequestServer{
	private String serverCategoryStr = "";// 服务器地址
	private String url = "http://109.105.3.230:8080/ChatBotServer/login";
	private static final int REQUEST_TIMEOUT = 1 * 1000;// 设置请求超时10秒钟
	private static final int SO_TIMEOUT = 5 * 1000; // 设置等待数据超时时间10秒钟

	public HttpRequestServer() {
		Context context = MyApplication.getInstance();
		PreferenceService sharePreferenceService = new PreferenceService(
				context,"preference");
		//获得服务器目录
		try {
			serverCategoryStr = sharePreferenceService.getString("serverCategoryStr");
			//if (serverCategoryStr.equals("null"))//启用默认目录
			//	serverCategoryStr = "http://109.105.3.230:8080/ChatBotServer/";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
/**
 * 用户注册
 * @param name 
 * @param pwd
 * @return
 * @throws ClientProtocolException
 * @throws JSONException
 * @throws IOException
 */
	public JSONObject regist(String name, String pwd)
			throws ClientProtocolException, JSONException, IOException {
		url = serverCategoryStr + Constants.URL_REGISTER;
		return requestServer(0, name, pwd, Constants.REGIST, "");
	}
/**
 * 用户登录
 * @param name
 * @param pwd
 * @return
 * @throws ClientProtocolException
 * @throws JSONException
 * @throws IOException
 */
	public JSONObject login(String name, String pwd)
			throws ClientProtocolException, JSONException, IOException {
		url = serverCategoryStr + Constants.URL_LOGIN;
		return requestServer(0, name, pwd, Constants.LOGIN, "");
	}
/**
 * 更改在线状态
 * @param userId
 * @param status
 * @return
 * @throws ClientProtocolException
 * @throws JSONException
 * @throws IOException
 */
	public boolean changeOnlineStatus(int userId, String status){
		url = serverCategoryStr + Constants.URL_ONLINE_STATUS;
		Log.v("myTagURL", url);
		JSONObject jobj;
		try {
			jobj = requestServer(userId, "name", "pwd", Constants.ONLINE_STATUS,
					status);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			return false;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		if(jobj==null)
			return false;
		Log.v("XXXXXXX00000000xx", jobj.toString());
	    String responseStatus;
		try {
			responseStatus = jobj.getString(Constants.STATUS);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	    if(responseStatus.equals(Constants.SUCCESS))
	    	return true;
	    return false;
	}
/**
 * 获得好友列表
 * @param userId
 * @return 
 * @throws ClientProtocolException
 * @throws JSONException
 * @throws IOException
 */
	public JSONObject getFriendsList(int userId)
			throws ClientProtocolException, JSONException, IOException {
		url = serverCategoryStr + Constants.URL_FRIENDSLIST;
		return requestServer(userId, "", "", Constants.REQUEST_FRIENDSLIST, "");
	}
/**
 * 通用请求服务器函数
 * @param userId
 * @param name
 * @param pwd
 * @param requestType
 * @param status
 * @return
 * @throws JSONException
 * @throws ClientProtocolException
 * @throws IOException
 */
	private JSONObject requestServer(int userId, String name, String pwd,
			String requestType, String status) throws JSONException,
			ClientProtocolException, IOException {
		// 不加这一段则会,错误信息为android.os.networkonmainthreadexception
		// 在Android2.2以后必须添加以下代码
		// 本应用采用的Android4.0
		// 设置线程的策略
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.permitAll() // 此处为允许磁盘读写和网络访问
				.penaltyLog() // 打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
				.build());

		HttpPost request = new HttpPost(url);

		// 先封装一个 JSON 对象
		JSONObject param = new JSONObject();
		param.put(Constants.TYPE, requestType);
		param.put(Constants.USER_NAME, name);
		param.put(Constants.USER_ID, userId);
		param.put(Constants.USER_PASSWORD, pwd);

		param.put(Constants.ONLINE_VALUE, status);
		// 绑定到请求 Entry
		StringEntity se = new StringEntity(param.toString());
		request.setEntity(se);
		// 发送请求
		HttpClient httpclient = getHttpClient();

		HttpResponse httpResponse = httpclient.execute(request);
		JSONObject result = null;
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 得到应答的字符串,这也是一个 JSON 格式保存的数据
			String retSrc = null;
			retSrc = EntityUtils.toString(httpResponse.getEntity());
			JSONObject jtmpJsonObject = new JSONObject(retSrc);
			String str = jtmpJsonObject.getString("dataMap");// 此处"dataMap"与服务器关联
			result = new JSONObject(str);
		}
		return result;
	}
  
	private HttpClient getHttpClient() {
		BasicHttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
		HttpClient httpclient = new DefaultHttpClient(httpParams);
		return httpclient;
	}
}


 

 类似资料:

相关阅读

相关文章

相关问答