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中设置相应的请求头内容即可。根据实际需要修改即可