java 实现http协议发送接收数据

2024-08-23 20:38

本文主要是介绍java 实现http协议发送接收数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

java模拟 post/get方式发送数据   main方法中用的是post

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;public class httpurl {private static final String TAG = "netUtils";/*** 使用post方式登陆** @param username* @param password* @return*/public static void main(String []args){httpurl test=new httpurl();test.loginOfPost("niha","qwer1234");}public static String loginOfPost(String username, String password) {HttpURLConnection conn = null;try {// 创建一个URL对象URL mURL = new URL("http://localhost:12001");// 调用URL的openConnection()方法,获取HttpURLConnection对象conn = (HttpURLConnection) mURL.openConnection();conn.setRequestMethod("POST");// 设置请求方法为post/* conn.setReadTimeout(5000);// 设置读取超时为5秒conn.setConnectTimeout(10000);// 设置连接网络超时为10秒*/conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容int len=0;String path="E:\\private_project\\github_project\\nsar\\test.txt";// post请求的参数byte[] buf= new byte[10240];FileInputStream fis=new FileInputStream(path);while((len = fis.read(buf)) != -1){System.out.print(len);}
//            String data = "username=" + username + "&password=" + password;// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
//            out.write(data.getBytes());out.write(buf);out.flush();out.close();int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法if (responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {
//                Log.i(TAG, "访问失败" + responseCode);System.out.print("访问失败");}} catch (Exception e) {e.printStackTrace();} finally {if (conn != null) {conn.disconnect();// 关闭连接}}return null;}/*** 使用get方式登陆** @param username* @param password* @return*/public static String loginOfGet(String username, String password) {HttpURLConnection conn = null;String data = "username=" + URLEncoder.encode(username) + "&password="+ URLEncoder.encode(password);String url = "http://192.168.0.100:8080/android/servlet/LoginServlet?"+ data;try {// 利用string url构建URL对象URL mURL = new URL(url);conn = (HttpURLConnection) mURL.openConnection();conn.setRequestMethod("GET");conn.setReadTimeout(5000);conn.setConnectTimeout(10000);int responseCode = conn.getResponseCode();if (responseCode == 200) {InputStream is = conn.getInputStream();String state = getStringFromInputStream(is);return state;} else {
//                Log.i(TAG, "访问失败" + responseCode);System.out.print("访问失败");}} catch (Exception e) {e.printStackTrace();} finally {if (conn != null) {conn.disconnect();}}return null;}/*** 根据流返回一个字符串信息         ** @param is* @return* @throws IOException*/private static String getStringFromInputStream(InputStream is)throws IOException {ByteArrayOutputStream os = new ByteArrayOutputStream();// 模板代码 必须熟练byte[] buffer = new byte[1024];int len = -1;// 一定要写len=is.read(buffer)// 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);}is.close();String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)os.close();return state;}
}


java 模拟服务器端接收post/get数据  实现时不需要向客户端返回数据,只需要接受客户端发过来的数据 所以response 注释掉了

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;/*** Created by lpeiz on 2016/9/26.*/
public class Server {public static void main(String[] args) {try {ServerSocket serverSocket = new ServerSocket(12001);
//            System.out.println("HTTP Server (only POST implemented) is ready and is listening on Port Number 12001 \n");while(true) {Socket clientSocket = serverSocket.accept();
//                System.out.println(clientSocket.getInetAddress().toString() + " " + clientSocket.getPort());BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//                OutputStream out = clientSocket.getOutputStream();String temp;int i=1001;while((temp=in.readLine()) != null)System.out.println(temp+i++);
//                String response = "HTTP/1.1 200 OK\n\r";
//                response = response + "Date: Fri, 04 May 2001 20:08:11 GMT\n\r";
//                response = response + "Server: Sanjits Server\n\r";
//                response = response + "Connection: close\n\r";
//                response = response + "1";
//                byte[] bytes = response.getBytes();
//                byte[]bytes=new byte[1024];
//                out.write(bytes);
//                out.flush();in.close();
//                out.close();}} catch(Exception e) {System.out.println("ERROR: " + e.getMessage());System.exit(1);}}}

国庆节前看了一个案例  但是跑的时候发现是错误的 13年前的帖子,现在还用这计数也确实该多学点先进的技术了

https://coderanch.com/t/205623/java/Java-Http-Server-Java-Http

对客户端的程序参照网上找到的其他成功的程序 改造了一下,加了两行发现成功了。。。

 con.setReadTimeout(5000);// 设置读取超时为5秒con.setConnectTimeout(10000);// 设置连接网络超时为10秒
就是这个控制时间的两行,还没搞清楚为什么。可能是类似jdbc连接的时候的语句执行之后的刷新问题

public class Client {public static void main(String[] args) {try {URL url = new URL("http://localhost:12001");HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setDoOutput(true);
//            con.setDoInput(true);con.setRequestMethod("POST");
//            con.setUseCaches(false);con.setReadTimeout(5000);// 设置读取超时为5秒con.setConnectTimeout(10000);// 设置连接网络超时为10秒String test = "<name>Hello</name>";byte[] bytes = test.getBytes();//            con.setRequestProperty("Content-type", "text/html");OutputStream out = con.getOutputStream();out.write(bytes);out.flush();out.close();BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));String temp;while((temp = in.readLine()) != null)System.out.println(temp);
//            out.close();in.close();con.disconnect();} catch(Exception e) {e.printStackTrace();System.exit(1);}}}





这篇关于java 实现http协议发送接收数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1100443

相关文章

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja