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

相关文章

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque