使用HttpURLConnection向服务器发送post和get请求

一,创建一个javaweb工程,在此工程下创建一个servlet类,在此类下搭建好接收get和post请求的服务器。服务器的代码如下:

<span style="font-size:18px;">package cn.edu.qf;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/UrlServer")
public class UrlServer extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// req.setCharacterEncoding("utf-8"); //POST使用此方法
		// 接收客户端的请求信息
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		// 解决中文乱码问题
		byte[] name = username.getBytes("ISO-8859-1"); // 先把接收的字节转换为字符
		username = new String(name, "UTF-8"); // 再把字符转换为字节

		System.out.println(username + "\t" + password);

		// 通过输出流,把响应结果写出去
		OutputStream os = resp.getOutputStream();
		if ("张三".equals(username) && "123".equals(password)) {
			os.write("success".getBytes());
		} else {
			os.write("fail".getBytes());
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码
		req.setCharacterEncoding("UTF-8");

		// 接收客户端的请求信息
		String username = req.getParameter("username");
		String password = req.getParameter("password");

		System.out.println(username + "\t" + password);
		
		// 通过输出流,把响应结果写出去
		OutputStream os = resp.getOutputStream();
		if ("张三".equals(username) && "123".equals(password)) {
			os.write("success".getBytes());
		} else {
			os.write("fail".getBytes());
		}
	}
}</span>

二,创建一个java工程,在此工程下创建一个实现get请求的java类:

<span style="font-size:18px;">package cn.edu.qf;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class TestUrlGet {
	public static void main(String[] args) {
		try {
			//对输入的内容进行编码,防止中文乱码
			String username = URLEncoder.encode("张三", "UTF-8");
			
			//对应GET请求,要把请求信息拼接在url后面
			URL url = new URL("http://localhost:8080/day26_server/UrlServer?username="+username+"&password=123");
		
			//调用url的openConnection()方法,获得连接对象
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			//设置HttpURLConnection的属性
			conn.setRequestMethod("GET");
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			
			//只是建立一个连接, 并不会发送真正http请求  (可以不调用)
			conn.connect();
			
			//通过响应码来判断是否连接成功
			if (conn.getResponseCode() == 200) {
				//获得服务器返回的字节流
				InputStream is = conn.getInputStream();
				
				//内存输出流,适合数据量比较小的字符串 和 图片
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[1024];
				int len = 0;
				while((len = is.read(buf))!=-1){
					baos.write(buf, 0, len);
				}
				//可使用 toByteArray() 和 toString() 获取数据。
				byte[] result = baos.toByteArray();
				System.out.println(new String(result));
				is.close();
				System.out.println("客户端执行完毕!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}</span>

三,在java工程下,再创建一个实现post请求的Java类:

<span style="font-size:18px;">package cn.edu.qf;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class TestUrlPost {
	public static void main(String[] args) {
		try {
			//post请求和get请求的最大不同就是提交请求信息的方式,post是通过把请求信息封装在http请求头中发送出去的
			URL url = new URL("http://localhost:8080/day26_server/UrlServer");
			
			//获得连接对象
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			//设置属性
			conn.setRequestMethod("POST");
			conn.setReadTimeout(5000);
			conn.setConnectTimeout(5000);
			
			//设置输入流和输出流,都设置为true
			conn.setDoOutput(true);
			conn.setDoInput(true);
			
			//设置http请求头(可以参照:http://tools.jb51.net/table/http_header)
			conn.setRequestProperty("Accept", "text/plain, text/html");//指定客户端能够接收的内容类型
			conn.setRequestProperty("Connection", "keep-alive"); //http1.1
			
			//封装要提交的数据
			String name = URLEncoder.encode("张三", "UTF-8");
			String message = "username="+name+"&password=123";
			
			//把提交的数据以输出流的形式提交到服务器
			OutputStream os = conn.getOutputStream();
			os.write(message.getBytes());
			
			//通过响应码来判断是否连接成功
			if (conn.getResponseCode() == 200) {
				//获得服务器返回的字节流
				InputStream is = conn.getInputStream();
				
				//内存输出流,适合数据量比较小的字符串 和 图片
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[1024];
				int len = 0;
				while((len = is.read(buf))!=-1){
					baos.write(buf, 0, len);
				}
				//可使用 toByteArray() 和 toString() 获取数据。
				byte[] result = baos.toByteArray();
				System.out.println(new String(result));
				is.close();
				System.out.println("客户端执行完毕!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}</span>


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值