javahttp請求
A. java實現攔截HTTP請求的幾種方式
在Java的服務端開發當中,攔截器是很常見的業務場景,這里對Java開發當中幾種常見的攔截器的實現方式進行記錄和分析。案例說明基於Spring Boot環境。
一:實現javax.servlet.Filter介面(使用過濾器方式攔截請求)
import org.springframework.stereotype.Component;import javax.servlet.*;import java.io.IOException;import java.util.Date;@Componentpublic class TimeInterceptor implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("time filter init");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("time filter start");long start = new Date().getTime();filterChain.doFilter(servletRequest, servletResponse);System.out.println("time filter 耗時:"+(new Date().getTime()-start));System.out.println("time filter finish");}@Overridepublic void destroy() {System.out.println("time filter destroy");}}
如使用@Compent註解聲明不需要加入其它配置即可使得攔截器生效,但是默認攔截/*,會攔截所有請求。
二:使用@Bean注入自定義攔截器,依然上面的代碼,去掉@Compent註解,創建TimeWebConfig配置類:
import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.ArrayList;import java.util.List;@Configurationpublic class TimeWebConfig {@Beanpublic FilterRegistrationBean timeFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();TimeInterceptor interceptor = new TimeInterceptor();registrationBean.setFilter(interceptor);List<String> urls = new ArrayList<>();urls.add("/user/*");registrationBean.setUrlPatterns(urls);return registrationBean;}}
上面這兩種攔截請求的實現是基於JavaEE提供的Filter介面實現的,缺點在於,該攔截器實際上是一個過濾器,執行代碼的方法doFilter只提供了request,response等參數,當請求進入被過濾器攔截的時候,我們並不知道這個請求是由哪個控制器的哪個方法來執行的。
三:使用springMVC提供的攔截器,實現org.springframework.web.servlet.HandlerInterceptor介面:
創建自定義的攔截器:
import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Date;@Componentpublic class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {System.out.println("preHandler");System.out.println(((HandlerMethod) handler).getBean().getClass().getName());System.out.println(((HandlerMethod) handler).getMethod().getName());httpServletRequest.setAttribute("start", new Date().getTime());return true;}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandler");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗時:"+(new Date().getTime()-start));}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗時:"+(new Date().getTime()-start));System.out.println("ex is:"+e);}}
創建配置類:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter {@Autowiredprivate MyInterceptor interceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(interceptor).addPathPatterns("/user/*").excludePathPatterns("/blog/*");}}
此種方式的攔截器當中我們能夠獲取攔截的請求對應的類和方法的相關信息,缺點在於該handler對象無法獲取具體執行方法的參數信息。
四:利用Spring的切面(AOP)實現攔截器:
引入jar包:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
創建切片類:
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;import java.util.Date;@Aspect@Componentpublic class TimeAspect {@Around("execution(* com.qinker.controller.UserController.*(..))")public Object handlerControllerMethod(ProceedingJoinPoint point) throws Throwable {System.out.println("time aspect start");long start = new Date().getTime();Object[] args = point.getArgs();for (Object obj : args) {System.out.println("arg is:"+obj);}Object obj = point.proceed();//具體方法的返回值System.out.println("aspect 耗時:"+(new Date().getTime()-start));System.out.println("time aspect end");return obj;}}
aspectj基於AOP實現的攔截器功能十分強大,具體詳解請參考spring官網網站的文檔。
B. java http請求直接請求地址的代碼怎麼寫
public static String do_get(String url) throws ClientProtocolException, IOException {
String body = "{}";
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
body = EntityUtils.toString(entity);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
C. java 怎麼接收http請求
你需要搭建一個伺服器,才能接受http請求。
D. javacurlhttp請求時間細節,怎麼實現
以下代碼是Java實現Http的Post、Get、代理訪問請求,可以參考一下
packagecom.snowfigure.kits.net;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStreamWriter;
importjava.io.UnsupportedEncodingException;
importjava.net.HttpURLConnection;
importjava.net.InetSocketAddress;
importjava.net.Proxy;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.List;
importjava.util.Map;
/**
*Http請求工具類
*@authorsnowfigure
*@since2014-8-2413:30:56
*@versionv1.0.1
*/
publicclassHttpRequestUtil{
staticbooleanproxySet=false;
staticStringproxyHost="127.0.0.1";
staticintproxyPort=8087;
/**
*編碼
*@paramsource
*@return
*/
publicstaticStringurlEncode(Stringsource,Stringencode){
Stringresult=source;
try{
result=java.net.URLEncoder.encode(source,encode);
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
return"0";
}
returnresult;
}
(Stringsource){
Stringresult=source;
try{
result=java.net.URLEncoder.encode(source,"GBK");
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
return"0";
}
returnresult;
}
/**
*發起http請求獲取返回結果
*@paramreq_url請求地址
*@return
*/
publicstaticStringhttpRequest(Stringreq_url){
StringBufferbuffer=newStringBuffer();
try{
URLurl=newURL(req_url);
HttpURLConnectionhttpUrlConn=(HttpURLConnection)url.openConnection();
httpUrlConn.setDoOutput(false);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
//將返回的輸入流轉換成字元串
InputStreaminputStream=httpUrlConn.getInputStream();
=newInputStreamReader(inputStream,"utf-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine())!=null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//釋放資源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
}catch(Exceptione){
System.out.println(e.getStackTrace());
}
returnbuffer.toString();
}
/**
*發送http請求取得返回的輸入流
*@paramrequestUrl請求地址
*@returnInputStream
*/
(StringrequestUrl){
InputStreaminputStream=null;
try{
URLurl=newURL(requestUrl);
HttpURLConnectionhttpUrlConn=(HttpURLConnection)url.openConnection();
httpUrlConn.setDoInput(true);
httpUrlConn.setRequestMethod("GET");
httpUrlConn.connect();
//獲得返回的輸入流
inputStream=httpUrlConn.getInputStream();
}catch(Exceptione){
e.printStackTrace();
}
returninputStream;
}
/**
*向指定URL發送GET方法的請求
*
*@paramurl
*發送請求的URL
*@paramparam
*請求參數,請求參數應該是name1=value1&name2=value2的形式。
*@returnURL所代表遠程資源的響應結果
*/
publicstaticStringsendGet(Stringurl,Stringparam){
Stringresult="";
BufferedReaderin=null;
try{
StringurlNameString=url+"?"+param;
URLrealUrl=newURL(urlNameString);
//打開和URL之間的連接
URLConnectionconnection=realUrl.openConnection();
//設置通用的請求屬性
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//建立實際的連接
connection.connect();
//獲取所有響應頭欄位
Map<String,List<String>>map=connection.getHeaderFields();
//遍歷所有的響應頭欄位
for(Stringkey:map.keySet()){
System.out.println(key+"--->"+map.get(key));
}
//定義BufferedReader輸入流來讀取URL的響應
in=newBufferedReader(newInputStreamReader(
connection.getInputStream()));
Stringline;
while((line=in.readLine())!=null){
result+=line;
}
}catch(Exceptione){
System.out.println("發送GET請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸入流
finally{
try{
if(in!=null){
in.close();
}
}catch(Exceptione2){
e2.printStackTrace();
}
}
returnresult;
}
/**
*向指定URL發送POST方法的請求
*
*@paramurl
*發送請求的URL
*@paramparam
*請求參數,請求參數應該是name1=value1&name2=value2的形式。
*@paramisproxy
*是否使用代理模式
*@return所代表遠程資源的響應結果
*/
publicstaticStringsendPost(Stringurl,Stringparam,booleanisproxy){
OutputStreamWriterout=null;
BufferedReaderin=null;
Stringresult="";
try{
URLrealUrl=newURL(url);
HttpURLConnectionconn=null;
if(isproxy){//使用代理模式
@SuppressWarnings("static-access")
Proxyproxy=newProxy(Proxy.Type.DIRECT.HTTP,newInetSocketAddress(proxyHost,proxyPort));
conn=(HttpURLConnection)realUrl.openConnection(proxy);
}else{
conn=(HttpURLConnection)realUrl.openConnection();
}
//打開和URL之間的連接
//發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");//POST方法
//設置通用的請求屬性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.connect();
//獲取URLConnection對象對應的輸出流
out=newOutputStreamWriter(conn.getOutputStream(),"UTF-8");
//發送請求參數
out.write(param);
//flush輸出流的緩沖
out.flush();
//定義BufferedReader輸入流來讀取URL的響應
in=newBufferedReader(
newInputStreamReader(conn.getInputStream()));
Stringline;
while((line=in.readLine())!=null){
result+=line;
}
}catch(Exceptione){
System.out.println("發送POST請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOExceptionex){
ex.printStackTrace();
}
}
returnresult;
}
publicstaticvoidmain(String[]args){
//demo:代理訪問
Stringurl="http://api.adf.ly/api.php";
Stringpara="key=youkeyid&youuid=uid&advert_type=int&domain=adf.ly&url=http://somewebsite.com";
Stringsr=HttpRequestUtil.sendPost(url,para,true);
System.out.println(sr);
}
}
E. java 怎麼接收http請求
用servlet接收。
具體步驟是寫一個類繼承HttpServlet,如果是接收get請求就重寫doGet(HttpServletRequest,HttpServletResponse),接收post就重寫doPost(HttpServletRequest,HttpServletResponse),共同處理post和get就重寫service(HttpServletRequest,HttpServletResponse)
其次在web.xml定義servlet標簽,以及你這個servlet要處理的請求mapping
最後把項目部署在tomcat之類的web容器中即可。
如果使用框架的話就另當別論了,比如spring 的DispatcherServlet。當然你也可以自己寫servlet。
F. 怎樣用JAVA實現模擬HTTP請求,得到伺服器的響應時間等參數
問題簡化一下:對一個ip,一個線程請求100次。該次請求的響應時間為調用httpClient前的響應時間減去接收到httpClient響應的時間。注意,本次請求是否有效要判斷。平均響應時間和最大響應時間只不過是響應時間的統計而已,可以用資料庫來做。
就是說資料庫記錄每次測試請求的響應時間,成功與否。統計數據最後出來。
只所以用多線程,是因為單線程順序請求100次,不能模擬伺服器真正的情況。
G. java 怎麼手動編寫http請求頭
實現思路就是先定義請求頭內容,之後進行請求頭設置。
定義請求頭
LinkedHashMap<String,String> headers = new LinkedHashMap<String,String>();
headers.put("Content-type","text/xml");
headers.put("Cache-Control", "no-cache");
headers.put("Connection", "close");
給HttpPost 設置請求頭
HttpPost httpPost = new HttpPost("http://localhost:8080/root");
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
備註:只需要在map中設置相應的請求頭內容即可。根據實際需要修改即可
H. java http請求中文路徑
不能用中文的,把中文的子文件夾名改為英語,java的路徑是不能有中文出現的