Java 中怎样在程序中设置代理服务器

Java 中怎样在程序中设置代理服务器,第1张

你的问题应该是:在java中通过编程设置代理服务器并访问网络,现在作答如下:

1,讲解一下基础知识:

HTTP:是应用层协议,是基于传输层协议的。

TCP: 是传输层协议,是基于网络层协议的。

IP: 是网络层协议。

一个TCP的连接要进行三次握手(就像转户口一样,不详说),HTTP只是一个应用协议,也就是相当于一个自定义协议,即其没有对底层的传输方式进行干涉,只是对数据内容格式进行了定义。

2,

我们再说说HTTP代理,从上可以理解,HTTP代理服务器就是这样一台机器:你把所有的HTTP请求都发到这个

HTTP代理服务器,然后这个HTTP代理服务器请求你要访问的最终地址,把响应回传给你。这里还要注意它代理的是HTTP协议,而HTTP又是基于

TCP的,也就是说这个服务器代理的是指定HTTP内容格式的TCP连接。再说下去也没意思了,看以下代码:

//以下地址是代理服务器的地址

Socket socket = new Socket("1012188", 80);

//写与的内容就是遵循HTTP请求协议格式的内容,请求百度

socketgetOutputStream()write(new String("GET http://wwwbaiducom/ HTTP/11\r\n\r\n")getBytes());

byte[] bs = new byte[1024];

InputStream is = socketgetInputStream();

int i;

while ((i = isread(bs)) > 0) {

Systemoutprintln(new String(bs, 0, i));

}

isclose();

3,当然在Java中,有Proxy代理上网的使用,此时使用URL(HTTP)就不涉及Socket(TCP)了,看如下代码

//设置代理

SystemsetProperty("httpproxySet", "true");

SystemsetProperty("httpproxyHost", "1012188");

SystemsetProperty("httpproxyPort", "80");

//直接访问目的地址

URL url = new URL("http://wwwbaiducom");

URLConnection con = urlopenConnection();

InputStreamReader isr = new InputStreamReader(congetInputStream());

char[] cs = new char[1024];

int i = 0;

while ((i = isrread(cs)) > 0) {

Systemoutprintln(new String(cs, 0, i));

}

isrclose();

下面是我自己写的一个读取并显示txt文件的demo,希望对您有帮助。

public class Client {

public static void main(String[] args) {

ClientFrame f = new ClientFrame();

}

}

import javaawtBorderLayout;

import javaawtContainer;

import javaawtDimension;

import javaawtGridLayout;

import javaawtToolkit;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioIOException;

import javanetSocket;

import javanetUnknownHostException;

import javautilVector;

import javaxswingBorderFactory;

import javaxswingJButton;

import javaxswingJFrame;

import javaxswingJList;

import javaxswingJScrollPane;

import javaxswingJTextArea;

import javaxswingeventListSelectionEvent;

import javaxswingeventListSelectionListener;

public class ClientFrame extends JFrame implements ActionListener, ListSelectionListener{

private JList list = null;

private JButton sbtn = null;

private JButton cbtn = null;

private Vector v = null;

private JTextArea txt = null;

private Container control = null;

private Container btn = null;

private Socket client = null;

private DataInputStream reader = null;

private DataOutputStream writer = null;

public ClientFrame(){

thislist = new JList();

thislistsetBorder(BorderFactorycreateTitledBorder("文件列表"));

thislistaddListSelectionListener(this);

thissbtn = new JButton("显示");

thissbtnaddActionListener(this);

thiscbtn = new JButton("清除");

thiscbtnaddActionListener(this);

thiscontrol = new Container();

thiscontrolsetPreferredSize(new Dimension(150, 400));

thiscontrolsetLayout(new BorderLayout());

thiscontroladd(new JScrollPane(thislist),BorderLayoutCENTER);

thisbtn = new Container();

thisbtnsetLayout(new GridLayout(1,2));

btnadd(sbtn);

btnadd(cbtn);

thiscontroladd(thisbtn,BorderLayoutSOUTH);

thistxt = new JTextArea();

thistxtsetEditable(false);

thistxtsetSize(350, 400);

thissetTitle("客户端");

thissetSize(500, 400);

thissetVisible(true);

Dimension displaySize = ToolkitgetDefaultToolkit()getScreenSize();

thissetLocation((displaySizewidth - thisgetWidth()) / 2, (displaySizeheight - thisgetHeight()) / 2);

thissetLayout(new BorderLayout());

thisadd(thiscontrol,BorderLayoutWEST);

thisadd(new JScrollPane(thistxt),BorderLayoutCENTER);

thissetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

try {

//thisclient = new Socket("1921683234",6666);

thisclient = new Socket("1921681100",6666);

thisreader = new DataInputStream(clientgetInputStream());

thiswriter = new DataOutputStream(clientgetOutputStream());

} catch (UnknownHostException e) {

eprintStackTrace();

} catch (IOException e) {

eprintStackTrace();

}

}

public void actionPerformed(ActionEvent event){

if(eventgetSource() == sbtn){

if(v == null){

v = new Vector();

}

else{

vclear();

}

try {

writerwriteUTF("getfilelist");

writerflush();

String t = readerreadUTF();

while( t != null && !tequals("")){

vadd(t);

t = readerreadUTF();

}

} catch (UnknownHostException e) {

eprintStackTrace();

} catch (IOException e) {

eprintStackTrace();

}

thislistsetListData(v);

}

if(eventgetSource() == cbtn){

thistxtsetText("");

}

}

public void valueChanged(ListSelectionEvent e) {

int i = thislistgetSelectedIndex();

if (! thislistgetValueIsAdjusting() && i != -1) {

try {

writerwriteUTF("getfilecontent_" + i);

writerflush();

String tmp = readerreadUTF();

thistxtsetText(tmp);

} catch (IOException e1) {

e1printStackTrace();

}

}

}

}

import javaioDataInputStream;

import javaioDataOutputStream;

import javaioFile;

import javaioFileInputStream;

import javaioIOException;

import javaioInputStreamReader;

import javaioReader;

import javanetServerSocket;

import javanetSocket;

import javautilArrayList;

import javautilIterator;

public class Server {

static ArrayList<File> fileArray = new ArrayList<File>();

public static void main(String args[]) {

ServerSocket server = null;

Socket client = null;

String cmd = "";

try {

server = new ServerSocket(6666);

client = serveraccept();

DataInputStream reader = new DataInputStream(clientgetInputStream());

DataOutputStream writer = new DataOutputStream(clientgetOutputStream());

while(true){

cmd = readerreadUTF();

Systemoutprintln(cmd);

if(cmdequals("getfilelist")){

fileArrayclear();

//fileArray = getFile(new File("D:/tmp"));

fileArray = getFile(new File("D:/学习/教程/学习笔记"));

String fn = "";

for(int k = 0; k < fileArraysize(); k ++){

fn = fileArrayget(k)getName();

writerwriteUTF(fn);

writerflush();

}

writerwriteUTF("");

}

if(cmdstartsWith("getfilecontent_")){

int i = IntegerparseInt(cmdsplit("_")[1]);

File f = fileArrayget(i);

Reader in = new InputStreamReader(new FileInputStream(f));

int tempbyte;

String str = "";

while ((tempbyte = inread()) != -1) {

str += (char)tempbyte;

//Systemoutprintln(str);

}

inclose();

writerwriteUTF(str);

}

}

} catch (IOException e) {

eprintStackTrace();

}

}

private static ArrayList<File> getFile(File f) {

File[] ff = flistFiles();

for (File child : ff) {

if (childisDirectory()) {

getFile(child);

} else {

fileArrayadd(child);

}

}

return fileArray;

}

}

首先服务器IP是动态的,这个接口还怎么访问呢?

所以,应该是要请求一个固定可访问的接口,然后这个接口去访回动态的其他服务器IP和端口,而这端口和IP是没办法在本机获取,需要在想要被访问的程序启动时,将其IP和端口写入共享区域(数据库,共享内存等),固定的获取接口根据条件获取动态IP和端口。

package comtemptest;

import javaio;

import javatextSimpleDateFormat;

import javautilLocale;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

public class Test {

static long start=0;

static long end=0;

static long run;

static boolean view=true;

static SimpleDateFormat sdf = new SimpleDateFormat("", LocaleSIMPLIFIED_CHINESE);

public static void start(){

start=SystemcurrentTimeMillis();

}

public static void end(){

end=SystemcurrentTimeMillis();

}

public static void run (HttpServletRequest request) throws IOException{

write(" -------------------");

write("xx"); // 写内容到d:/abctxt

write(" -------------------\r\n");

}

}

public static void write(String content) throws IOException {

BufferedWriter out = null;

try {

out = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream("d:/abctxt", true)));

outwrite(content+"\r\n");

} catch (Exception e) {

eprintStackTrace();

} finally {

try {

outclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » Java 中怎样在程序中设置代理服务器

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情