訪問url獲取返回值
① php中怎麼獲取一個URL的返回數據
http get一下就返回源碼了。。比如 url為 target/XX.PHP?V=1
用游覽器訪問直接下載一個MP3 可以參考如下代碼:
<?php
$data = file_get_contents('target/XX.PHP?V=1');
file_put_contents('test.mp3', $data, true);
?>
② java獲取伺服器文件,怎樣用url返回
下面提供二種方法會使用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;
(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();
}
第二種方法:
代碼如下:
(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;
}
總結:多練習代碼,熟練之後才能更快速的去了解代碼的學習的方法。多去獲取一些思維方面的書籍可以看看。