Java如何利用url下载MP3保存的方法:
1 /** ;
2 * TODO 下载文件到本地 ;
3 * @author nadim ;
4 * @date Sep 11, 2015 11:45:31 AM ;
5 * @param fileUrl 远程地址 ;
6 * @param fileLocal 本地路径 ;
7 * @throws Exception ;
8 */ ;
9 public void downloadFile(String fileUrl,String fileLocal) throws Exception {;
10 URL url = new URL(fileUrl)
11 HttpURLConnection urlCon = (HttpURLConnection) url.openConnection()
12 urlCon.setConnectTimeout(6000)
13 urlCon.setReadTimeout(6000)
14 int code = urlCon.getResponseCode()
15 if (code != HttpURLConnection.HTTP_OK) {
16 throw new Exception("文件读取失败")
17 }
18 //读文件流;
19 DataInputStream in = new DataInputStream(urlCon.getInputStream())
20 DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal))
21 byte[] buffer = new byte[2048]
22 int count = 0
23 while ((count = in.read(buffer)) >0) {;
24 out.write(buffer, 0, count)
25 }
26 out.close()
27 in.close()
28 }。
Java是一门面向对象编程语言,不仅吸收了C++语言的各种优点,还摒弃了C++里难以理解的多继承、指针等概念,因此Java语言具有功能强大和简单易用两个特征。
Java语言作为静态面向对象编程语言的代表,极好地实现了面向对象理论,允许程序员以优雅的思维方式进行复杂的编程 。
下面提供二种方法会使用java发送url请求,并获取服务器返回的值
第一种方法:
代码如下:
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.NameValuePair
import org.apache.http.client.HttpClient
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.message.BasicNameValuePair
import org.apache.http.params.CoreConnectionPNames
import org.apache.http.util.EntityUtils
publicstaticStringsendUrlRequest(StringurlStr,Stringparam1,Stringparam2)throwsException{
StringtempStr=null
HttpClienthttpclient=newDefaultHttpClient()
Propertiesproperties=newProperties()
HttpEntityentity=null
StringxmlContent=""
try
{
//设置超时时间
httpclient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,20000)
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,20000)
//封装需要传递的参数
List<NameValuePair>nvps=newArrayList<NameValuePair>()
nvps.add(newBasicNameValuePair("mainMemoCode",strmainMemoCode))
nvps.add(newBasicNameValuePair("recordPassWord",strrecordPassWord))
//客户端的请求方法类型
HttpPosthttpPost=newHttpPost(urlStr)
httpPost.setEntity(newUrlEncodedFormEntity(nvps,"GBK"))
HttpResponseresponse=httpclient.execute(httpPost)
//获取服务器返回Http的Content-Type的值
tempStr=response.getHeaders("Content-Type")[0].getValue().toString()
//获取服务器返回页面的值
entity=response.getEntity()
xmlContent=EntityUtils.toString(entity)
Stringstrmessage=null
System.out.println(xmlContent)
System.out.println(response.getHeaders("Content-Type")[0].getValue().toString())
httpPost.abort()
}
catch(SocketTimeoutExceptione)
{
}
catch(Exceptionex)
{
ex.printStackTrace()
}
finally{
httpclient.getConnectionManager().shutdown()
}
第二种方法:
代码如下:
publicstaticStringsendUrlRequest(StringurlStr,Stringparam1,Stringparam2)throwsException{
HttpURLConnectionurl_con=null
try{
URLurl=newURL(urlStr)
StringBufferbankXmlBuffer=newStringBuffer()
//创建URL连接,提交到数据,获取返回结果
HttpURLConnectionconnection=(HttpURLConnection)url.openConnection()
connection.setRequestMethod("POST")
connection.setDoOutput(true)
connection.setRequestProperty("User-Agent","directclient")
PrintWriterout=newPrintWriter(newOutputStreamWriter(connection.getOutputStream(),"GBK"))
out.println(param)
out.close()
BufferedReaderin=newBufferedReader(newInputStreamReader(connection
.getInputStream(),"GBK"))
StringinputLine
while((inputLine=in.readLine())!=null){
bankXmlBuffer.append(inputLine)
}
in.close()
tempStr=bankXmlBuffer.toString()
}
catch(Exceptione)
{
System.out.println("发送GET请求出现异常!"+e)
e.printStackTrace()
}finally{
if(url_con!=null)
url_con.disconnect()
}
returntmpeStr
}
总结:多练习代码,熟练之后才能更快速的去了解代码的学习的方法。多去获取一些思维方面的书籍可以看看。