javahttp請求
『壹』 java如何調用對方http介面
你是指發送http請求嗎,可以使用Apache 的 HttpClient
//構建HttpClient實例
CloseableHttpClienthttpclient=HttpClients.createDefault();//設置請求超時時間
RequestConfigrequestConfig=RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(60000).build();//指定POST請求
HttpPosthttppost=newHttpPost(url);
httppost.setConfig(requestConfig);//包裝請求體
List<NameValuePair>params=newArrayList<NameValuePair>();params.addAll(content);
HttpEntityrequest=newUrlEncodedFormEntity(params,"UTF-8");//發送請求
httppost.setEntity(request);
=httpclient.execute(httppost);//讀取響應
HttpEntityentity=httpResponse.getEntity();Stringresult=null;if(entity!=null){
result=EntityUtils.toString(entity,"UTF-8");
}
『貳』 java http請求直接請求地址的代碼怎麼寫
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;
}
『叄』 java模擬http請求指定url
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
}
大體上就是這樣了。
『肆』 java 怎麼接收http請求
HttpURLConnection mHttpURLConnection = null;
URL mUrl = null;
InputStream inputStream = null;
try {
String url = UrlEncode(mFileType.getStrUrl(), "UTF-8");
//mUrl = new URL(mFileType.getStrUrl());
mUrl = new URL(url);
mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
mHttpURLConnection.setAllowUserInteraction(true);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Range", "bytes=" + startPos
+ "-" + endPos);
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
int responseCode = mHttpURLConnection.getResponseCode();
long length = mHttpURLConnection.getContentLength();
// 判斷請求是否成功處理
if (responseCode == HttpStatus.SC_OK||responseCode == HttpStatus.SC_PARTIAL_CONTENT) {
inputStream = mHttpURLConnection.getInputStream();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
『伍』 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官網網站的文檔。
『陸』 怎麼用java模擬http請求
/*
* 得到返回的內容
*/
public static String getResult(String urlStr, String content) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
追問:
沒注釋嗎?
追答:
/*
* 得到返回的內容
*/
public static String getResult(String urlStr, String content) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();//新建連接實例
connection.setDoOutput(true);//是否打開輸出流 true|false
connection.setDoInput(true);//是否打開輸入流true|false
connection.setRequestMethod("POST");//提交方法POST|GET
connection.setUseCaches(false);//是否緩存true|false
connection.connect();//打開連接埠
DataOutputStream out = new DataOutputStream(connection.getOutputStream());//打開輸出流往對端伺服器寫數據
out.writeBytes(content);//寫數據,也就是提交你的表單 name=xxx&pwd=xxx
out.flush();//刷新
out.close();//關閉輸出流
BufferedReader reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));//往對端寫完數據 對端伺服器返回數據 ,以BufferedReader流來讀取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();//關閉連接
}
}
return null;
}
『柒』 java 接受http請求
使用servlet
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Test() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收get請求
// 這里寫你接收request請求後要處理的操作
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收post請求
// 這里寫你接收request請求後要處理的操作
}
}
『捌』 java HTTP請求 處理
javax.servlet.http.HttpResponse類用於產生返回頁面.通過HttpResponse定義的方法getOutputStream()可以獲得ServletOutputStream的實例,這樣用戶就可以利用ServletOutputStream.write方法向輸出流中寫入返回頁面的內容. 但是ServletOutputStream使用的是預設的編碼方式,如果要使返回頁面中的中文字 符能夠正常顯示,最好顯示地指定所用的字元編碼方式. 通常需要構造一個 OutputStreamWriter , 常式如下:
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(out,"GB2312");
ow.write("這是測試");
ow.flush();
ow.close();
}
『玖』 如何使用java發送post請求
/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
『拾』 java怎麼主動發送http請求
實現思路就是先定義請求頭內容,之後進行請求頭設置。
定義請求頭回
給HttpPost 設置請求頭
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 = new HttpPost("地址");
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key));
}
}
備註:只答需要在map中設置相應的請求頭內容即可。根據實際需要修改即可