java 实现http协议发送接收数据
来源:互联网 发布:linux shell 睡眠 编辑:程序博客网 时间:2024/05/14 03:35
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);}}}
0 0
- java 实现http协议发送接收数据
- C# 用HTTP协议发送、接收数据
- JAVA Http协议的发送接收
- 需要用C#http协议发送和接收数据
- 纯 java 实现 Http 资源读取工具,支持发送和接收数据
- Java Socket发送与接收HTTP消息简单实现
- Java Socket发送与接收HTTP消息简单实现
- Java Socket发送与接收HTTP消息简单实现
- Java Socket发送与接收HTTP消息简单实现
- Java Socket发送与接收HTTP消息简单实现
- UDP协议接收数据与发送数据
- 纯 java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包
- 纯 java 实现 Http 资源读取工具,支持发送和接收数据,不依赖任何第三方 jar 包
- java实现http post方法发送数据
- 使用UDP协议发送和接收数据
- 使用UDP协议发送和接收数据
- 使用UDP协议发送和接收数据
- TCP协议接收与发送数据
- 项目总结
- 操作系统实验之进程管理
- Babylon.js入门简介和开发实例
- matrix4
- 智能小车的制作(七)
- java 实现http协议发送接收数据
- POJ3624 Charm Bracelet
- ECMAScript5 中的数组方法 二十八
- 9.30补
- 第一篇 Frankle-Mccan去雾算法
- UGUI内核大探究(零)
- C++ 中随机函数 rand() 和 srand() 的用法
- 我的校招——南京烽火笔试+格力初面
- ogre 渲染流程