五.URLConnection与url对象交互

本文提供了一个使用 Java 的 URLConnection 类实现客户端与服务器 CGI 程序交互的示例。通过编码字符串并将其发送到指定 URL,然后读取服务器响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package myk;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class RequestURLConnection {

	/**
	 *与url对象交互
	 *java程序与服务器端的CGI进行交互
	 */
	public static void main(String[] args) {
		
		try {
			String string_vesion = URLEncoder.encode("sdghghjk");
			URL exampleURL = new URL("http://java.sun.com/cgi-bin/backwards");
			//建立连接
			URLConnection exampleConnection = exampleURL.openConnection();
			
			exampleConnection.setDoInput(true);
			exampleConnection.setDoOutput(true);
			
			//获取URLConnection的数据输出流
			PrintStream printStream = new PrintStream(new DataOutputStream(exampleConnection.getOutputStream()));
			//从输出流输出数据
			printStream.println(string_vesion);
			
			printStream.close();
			
			DataInputStream dis = new DataInputStream(exampleConnection.getInputStream());
			
			String inputLine;
			
			while((inputLine=dis.readLine())!=null){
				System.out.println(inputLine);
			}
			
			dis.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值