解决java代码无法通过vpn访问对端接口

来源:互联网 发布:淘宝直播达人淘在哪里 编辑:程序博客网 时间:2024/04/29 01:55

使用CCProxy设置代理

 


注:2.0.1.2为vpn虚拟网卡ip

 

 

然后java代码模拟http请求时添加代理:

 

public static String getHttp(String url,Stringparam) {

          String result = null ;

          InputStream in = null;

          try {

              Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1", Integer.valueOf("8188")));

              String urlNameString =url +"?" +param;

              URL realUrl = new URL(urlNameString);

              System.out.println(urlNameString);

              // 打开和URL之间的连接

              HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection(proxy);

              // 设置通用的请求属性

              connection.setRequestProperty("Connection","keep-alive");

              // 建立实际的连接

              connection.connect();

              // 定义 BufferedReader输入流来读取URL的响应

              in = connection.getInputStream();

              byte[]inByte =newbyte[in.available()];

              in.read(inByte, 0,in.available());

              result = new String(inByte,"utf-8");

              System.out.println(result);

          } catch (Exceptione) {

              System.out.println("发送GET请求出现异常!" + e);

              e.printStackTrace();

          }

          // 使用finally块来关闭输入流

          finally {

              try {

                  if (in !=null) {

                      in.close();

                  }

              } catch (Exceptione2) {

                  e2.printStackTrace();

              }

          }

          returnresult;

    }

原创粉丝点击