java-http通信调用与创建

java项目使用HTTP的请求。主要有两种方式:
使用JDK自带的java.net包下的HttpURLConnection方式。

使用apache的HttpClient方式。

一、使用JDK自带的java.net包下的HttpURLConnection方式。

方法摘要
abstract  void disconnect()
          指示近期服务器不太可能有其他请求。
 InputStream getErrorStream()
          如果连接失败但服务器仍然发送了有用数据,则返回错误流。
static boolean getFollowRedirects()
          返回指示是否应该自动执行 HTTP 重定向 (3xx) 的 boolean 值。
 String getHeaderField(int n)
          返回 nth 头字段的值。
 long getHeaderFieldDate(String name, long Default)
          返回解析为日期的指定字段的值。
 String getHeaderFieldKey(int n)
          返回 nth 头字段的键。
 boolean getInstanceFollowRedirects()
          返回此 HttpURLConnectioninstanceFollowRedirects 字段的值。
 Permission getPermission()
          返回一个权限对象,其代表建立此对象表示的连接所需的权限。
 String getRequestMethod()
          获取请求方法。
 int getResponseCode()
          从 HTTP 响应消息获取状态码。
 String getResponseMessage()
          获取与来自服务器的响应代码一起返回的 HTTP 响应消息(如果有)。
 void setChunkedStreamingMode(int chunklen)
          此方法用于在预先知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
 void setFixedLengthStreamingMode(int contentLength)
          此方法用于在预先已知内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
static void setFollowRedirects(boolean set)
          设置此类是否应该自动执行 HTTP 重定向(响应代码为 3xx 的请求)。
 void setInstanceFollowRedirects(boolean followRedirects)
          设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向(响应代码为 3xx 的请求)。
 void setRequestMethod(String method)
          设置 URL 请求的方法, GET POST HEAD OPTIONS PUT DELETE TRACE 以上方法之一是合法的,具体取决于协议的限制。
abstract  boolean usingProxy()
          指示连接是否通过代理。

注意:

HttpURLConnection为get请求时,urlConnection.setRequestMethod("GET");,需要注释outputStream = urlConnection.getOutputStream();,进行getOutputStream时,为把get请求自动转换为post请求,导致返回403

客户端:

请求接口

/**
      * 请求资源
      * @param http
      * @param message
      * @param type
      * @return
      */
    public static String httpRequestResources(String http,String message,String type) {
        String resultMsg = "";
        InputStreamReader iStreamReader = null;
        BufferedReader reader = null;
        OutputStream oStream  = null;
        OutputStreamWriter oStreamWriter= null;
        InputStream iStream = null;
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            URL url = new URL(http);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();//创建连接
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");//请求类型
            httpURLConnection.setRequestMethod(type);//请求方式
            httpURLConnection.setConnectTimeout(1000);//连接超时
            httpURLConnection.setReadTimeout(30000);//设置从主机读取数据超时
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            if (StringUtils.isNotEmpty(message)) {
                 oStream = httpURLConnection.getOutputStream();
                 oStreamWriter = new OutputStreamWriter(oStream, "UTF-8");//设置输出流
                oStreamWriter.write(message);
                oStreamWriter.flush();
            }
            int rCode = httpURLConnection.getResponseCode();
            if (rCode == HttpURLConnection.HTTP_OK) {
                iStream = httpURLConnection.getInputStream();
            }else {
                iStream = httpURLConnection.getErrorStream();
            }
            if (iStream != null) {
                iStreamReader = new InputStreamReader(iStream, "UTF-8");
            }
            if (iStreamReader != null) {
                reader = new BufferedReader(iStreamReader);
            }
            if (reader != null) {
                String len;
                while ((len = reader.readLine()) != null) {
                    resultMsg += len;                    
                }
            }
        } catch (Exception e) {
            logger.error("调取接口异常:"+http+"|||"+e.getMessage());
            
        }finally {
                try {
                    if(iStreamReader!=null)
                        iStreamReader.close();
                    if(reader!=null)
                        reader.close();
                    if(oStreamWriter!=null)
                        oStreamWriter.close();    
                    if(oStream!=null)
                        oStream.close();
                    if (iStream != null) {
                        iStream.close();
                    }
                } catch (IOException e) {
                    logger.error("调取接口httpRequestResources异常:"+e.getMessage()+";printStackTrace: "+e.getStackTrace());
                }
            
        }
        return resultMsg;
    }

服务端:

private void responseFunction(HttpServletRequest request, HttpServletResponse response) {
        request.setCharacterEncoding("utf-8");  
        response.setContentType("text/html;charset=utf-8");  
        String str=request.getParameter("xxx");//获得发送HTTP请求的参数   
        response.getWriter().write("{"message":"success"}");//向HTTP发送方返回响应数据  
    }

 例:

服务端创建http接口:

接口controller

package net.nblh.api.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.nblh.api.base.ApiBase;
import net.nblh.comm.response.ResponseResult;

/**
 * 接口
 * @author lijd
 *
 */
@RequestMapping("api/conferenceApprove")
@RestController
public class ConferenceApproveAPIController extends ApiBase{
    @RequestMapping(value="approve",method=RequestMethod.POST)
    @ResponseBody//http://172.19.82.47:1002/conf/api/conferenceApprove/approve
    public ResponseResult approve(HttpServletRequest request,HttpServletResponse response) throws Exception{
        JSONObject jsonObject =  new JSONObject();
        String data= IOUtils.toString(request.getInputStream());//获取传入的json
        jsonObject = JSON.parseObject(data);
        //....
        ResponseResult responseResult = new ResponseResult(ResponseResult.SUCCESSCODE);
        responseResult.setMsg("签批成功");
        return responseResult;
    }
}

@ControllerAdvice异常拦截

package net.nblh.api.base;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONException;

import net.nblh.comm.response.ResponseResult;

/**
 * 数据验证
 * @author lijd
 *
 */
@ControllerAdvice
public class ApiBase {
    
    @ExceptionHandler(JSONException.class)
    @ResponseBody
    public ResponseResult handlerJSONException(JSONException e) {
        ResponseResult responseResult = new ResponseResult(ResponseResult.FAILURECODE);
        responseResult.setMsg("json格式不正确");
        responseResult.setData(e.getMessage());
        return responseResult;
    }
}

shiro配置

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
      <!-- 指定URL拦截规则 -->
      <property name="filterChainDefinitions">
           <!--authc:代表shiro框架提供的一个过滤器,这个过滤器用于判断当前用户是否已经完成认证,如果当前用户已经认证,就放行,如果当前用户没有认证,跳转到登录页面
               anon:代表shiro框架提供的一个过滤器,允许匿名访问-->
           <value>
               /api/**/** = anon
           </value>
      </property>
</bean>
原文地址:https://www.cnblogs.com/lijianda/p/8962508.html