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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM