如何使用java调用url接口

Python017

如何使用java调用url接口,第1张

原贴地址http://yuanlijia1.iteye.com/blog/1088088

一、在java中调用url,并打开一个新的窗口 

Java代码

String url="http://10.58.2.131:8088/spesBiz/test1.jsp"  

String cmd = "cmd.exe /c start " + url   

  

try {   

 Process proc = Runtime.getRuntime().exec(cmd)   

 proc.waitFor()   

}   

catch (Exception e)   

{   

 e.printStackTrace()  

}

二、在java中调用url,后台调用。并取得返回值 

Java代码

URL U = new URL("http://10.58.2.131:8088/spesBiz/test1.jsp")  

URLConnection connection = U.openConnection()  

   connection.connect()  

    

   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))  

   String line  

   while ((line = in.readLine())!= null)  

   {  

    result += line  

   }  

   in.close()

1.编写useSourceViewer 类的基本框架,该类仅包括无返回值的main ()方法,该方法从参数中获取URL,通过输入缓冲和输出缓冲将该URL 原码输出。

2.编写useSourceViewer 类,代码如下:

import java.net.*

import java.io.*

public class useSourceViewer

{

public static void main (String[] args)

{

if (args.length >0)

{

try

{

//读入URL

URL u = new URL(args[0])

InputStream in = u.openStream( )

// 为增加性能存储输入流

in = new BufferedInputStream(in)

// 将输入流连接到阅读器

Reader r = new InputStreamReader(in)

int c

while ((c = r.read( )) != -1)

{

System.out.print((char) c)

}

Object o = u.getContent( )

System.out.println("I got a " + o.getClass().getName( ))

}

catch (MalformedURLException e)

{

System.err.println(args[0] + " is not a parseable URL")

}

catch (IOException e)

{

System.err.println(e)

}

} // end if

} // end main

} // end SourceViewer}

private static final String imgDir="C:/Program Files/Tencent/TM2009/Users/273367058/FileRecv"//这里填上图片目录全名就行了

static{

try{

File dir = new File(imgDir)

File[] imgFiles = dir.listFiles(new FilenameFilter(){

public boolean accept(File dir, String name) {

return name.toLowerCase().endsWith(".jpg")

}

})