java写socket请求

POST请求

public String XHttp(String SendData) {
		String ret = null;

		Socket mSocket = null;
		OutputStream os = null;
		InputStream ins = null;
		try {
			String host = getHost(url);
			mSocket = new Socket(host, port);
			os = mSocket.getOutputStream();
			ins = mSocket.getInputStream();
			StringBuffer sb = new StringBuffer();
			sb.append("POST ").append(postUrl).append(" HTTP/1.1")
					.append("\r\n");
			sb.append(
					"Accept: image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*")
					.append("\r\n");
			sb.append("Accept-Language: en-GB,en-US").append("\r\n");
			sb.append("Content-Type: application/x-www-form-urlencoded")
					.append("\r\n");
			sb.append(
					"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30618)")
					.append("\r\n");

			sb.append("Host: ").append(url).append(":").append(port)
					.append("\r\n");
			sb.append("Content-Length: ").append(SendData.length())
					.append("\r\n");
			sb.append("Connection: Keep-Alive").append("\r\n");
			sb.append("Cache-Control: no-cache").append("\r\n\r\n");
			sb.append(SendData);
			String Searchname_send = new String(sb.toString().getBytes(), "utf-8");
			os.write(Searchname_send.getBytes());
			os.flush();

			String line = null;
			int contentLength = 0;// 服务器发送回来的消息长度
			// 读取所有服务器发送过来的请求参数头部信息
			do {
				line = readLine(ins, 0);
				// 如果有Content-Length消息头时取出
				if (line.startsWith("Content-Length")) {
					contentLength = Integer.parseInt(line.split(":")[1].trim());
				}
				// 打印请求部信息
				// System.out.print(line);
//				Log.i(TAG, "line is " + line);

				// 如果遇到了一个单独的回车换行,则表示请求头结束
			} while (!line.equals("\r\n"));
			ret = readLine(ins, contentLength);
			// --输消息的体
//			Log.i(TAG, "ret is " + ret);
			// System.out.print(readLine(ins, contentLength));
			// sb = new StringBuffer();
			// BufferedReader br = new BufferedReader(new
			// InputStreamReader(ins));
			// String str = null;
			// while ((str = br.readLine()) != null) {
			// sb.append(str);
			// System.out.println(str);
			// }
			// br.close();
			// ret = sb.toString();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		finally {
			if (null != mSocket) {
				try {
					mSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != ins) {
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return ret;
	}
GET请求

	public String XHttp(String SendData) {
		//String ret = sendmsg("192.168.0.100",SendData);
		String ret = null;

		// String SendData =
		// "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request><method>login</method><username>ss</username><password>123</password></request>";
		Socket mSocket = null;
		OutputStream os = null;
		InputStream ins = null;
		try {
			String host = getHost(url);
//			System.out.println(host);
//			System.out.println(port);
			mSocket = new Socket(host, port);
			os = mSocket.getOutputStream();
			ins = mSocket.getInputStream();

			StringBuffer sb = new StringBuffer();

			sb.append("GET ").append(postUrl).append(" HTTP/1.1")
			.append("\r\n");
			sb.append("Host").append(": ").append(host).append(":")
			.append(port).append("\r\n");
			sb.append("Connection").append(": ").append("Close").append("\r\n");
			sb.append("Accept").append(": ").append("*/*").append("\r\n");
			sb.append("\r\n");// end
			sb.append("Content-Length: ").append(SendData.length())
					.append("\r\n");
			sb.append("Connection: Keep-Alive").append("\r\n");
			sb.append("Cache-Control: no-cache").append("\r\n\r\n");
			sb.append(SendData);

//			System.out.println("sb is " + sb);
			
			
			String Searchname_send = new String(sb.toString().getBytes(), "utf-8");
			
//			byte[] testbyte = Searchname_send.getBytes();
//			System.out.println("testbyte.length is "
//					+ testbyte.length);
//			for (int i = 0; i < testbyte.length; i++) {
//				String hex = Integer
//						.toHexString(testbyte[i] & 0xFF);
//				if (hex.length() == 1) {
//					hex = '0' + hex;
//				}
//				System.out.print(hex.toUpperCase() + " ");
//			}
			
			
//			os.write(sb.toString().getBytes());
			os.write(Searchname_send.getBytes());
			os.flush();

			String line = null;
			int contentLength = 0;// 服务器发送回来的消息长度
			// 读取所有服务器发送过来的请求参数头部信息
			do {
				line = readLine(ins, 0);
				// 如果有Content-Length消息头时取出
				if (line.startsWith("Content-Length")) {
					contentLength = Integer.parseInt(line.split(":")[1].trim());
				}
				// 打印请求部信息
				// System.out.print(line);
//				Log.i(TAG, "line is " + line);

				// 如果遇到了一个单独的回车换行,则表示请求头结束
			} while (!line.equals("\r\n"));
			ret = readLine(ins, contentLength);
			// --输消息的体
//			Log.i(TAG, "ret is " + ret);
			// System.out.print(readLine(ins, contentLength));
			// sb = new StringBuffer();
			// BufferedReader br = new BufferedReader(new
			// InputStreamReader(ins));
			// String str = null;
			// while ((str = br.readLine()) != null) {
			// sb.append(str);
			// System.out.println(str);
			// }
			// br.close();
			// ret = sb.toString();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		finally {
			if (null != mSocket) {
				try {
					mSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (null != ins) {
				try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return ret;
	}

public static String getHost(String url) {
		Pattern p = Pattern.compile("(http://|https://)?([^/]*)",
				Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(url);
		return m.find() ? m.group(2) : url;
	}

	private static String readLine(InputStream is, int contentLe)
			throws IOException {
		ArrayList lineByteList = new ArrayList();
		byte readByte;
		int total = 0;
		if (contentLe != 0) {
			do {
				readByte = (byte) is.read();
				lineByteList.add(Byte.valueOf(readByte));
				total++;
			} while (total < contentLe);// 消息体读还未读完
		} else {
			do {
				readByte = (byte) is.read();
				lineByteList.add(Byte.valueOf(readByte));
			} while (readByte != 10);
		}

		byte[] tmpByteArr = new byte[lineByteList.size()];
		for (int i = 0; i < lineByteList.size(); i++) {
			tmpByteArr[i] = ((Byte) lineByteList.get(i)).byteValue();
		}
		lineByteList.clear();

		return new String(tmpByteArr, encoding);
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要手JavaSocket Modbus,首先我们需要了解Modbus协议的工作原理。Modbus是一种常用于工业自动化领域的通信协议,用于在不同设备之间进行数据交换。 首先,我们需要创建一个Socket连接来与Modbus设备进行通信。可以使用Java提供的Socket类来实现。 接下来,我们需要根据Modbus协议的规范,构建Modbus请求报文。根据不同的功能码,请求报文的格式会有所不同。我们可以使用Java中的字节流或者字节数组来构建请求报文,并通过Socket发送给Modbus设备。 然后,我们需要等待Modbus设备的响应报文。可以使用JavaSocket类提供的InputStream来接收Modbus设备返回的数据。 接下来,我们需要解析Modbus设备返回的响应报文。根据Modbus协议的规范,响应报文的格式也会有所不同。我们可以使用Java的字节流或者字节数组来解析响应报文,并提取出需要的数据。 最后,根据需要,可以将获取到的数据进行处理和展示。 在编Socket Modbus代码时,我们需要了解Modbus协议的规范和各种功能码的定义。可以参考Modbus协议的官方文档或相关资料。 总结起来,手JavaSocket Modbus需要实现Socket连接的建立,构建Modbus请求报文,发送请求报文到Modbus设备,接收和解析Modbus设备的响应报文,并对获取到的数据进行处理。这需要对Modbus协议和Java Socket编程有一定的了解。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值