国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java 適合于restful規則的http通信

2019-11-06 06:07:38
字體:
來源:轉載
供稿:網友

java通信有很多種類可調用

最常用的是httpClient, PostMethod、GetMethod等這種的,他們的maven包:

 <dependency>                <groupId>commons-httpclient</groupId>                <artifactId>commons-httpclient</artifactId>                <version>3.1</version></dependency>

還有一種就是sun.net.www包中的原始http請求HttpURLConnection。在使用put請求時,PutMethod方法中的參數只能通過@QueryParam獲取,這與前端js代碼不一致,前端代碼是用@FormParam的,所以我們就用HttpURLConnection來實現了,詳情看本文的put請求方法調用。本文中用到的HttpClientResponse為自己寫的class,在文章最后

package com.flyread.optwebcontainer.biz.httPRequest;import org.apache.commons.httpclient.*;import org.apache.commons.httpclient.methods.DeleteMethod;import org.apache.commons.httpclient.methods.GetMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.params.HttpMethodParams;import sun.net.www.protocol.http.HttpURLConnection;import java.io.*;import java.net.URL;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.io.IOException;import java.io.InputStream;/** * http對象, * Created by sff on 2017/2/28. */public class HttpClientUtil{    /**     * get請求     * @param url     * @param params     * @return     */    public static  HttpClientResponse getHttp( String url, Map<String, String> params){        return getHttp(url, params, 60000);    }    public static  HttpClientResponse getHttp(String url, Map<String, String> params, int timeout){        HttpClient httpClient = new HttpClient();        GetMethod getMethod = new GetMethod(url);        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");        List<NameValuePair> list = new ArrayList<>();        for(Map.Entry<String, String> param : params.entrySet()){            list.add(new NameValuePair(param.getKey(), param.getValue()));        }        NameValuePair[] paramsArray = new NameValuePair[list.size()];        for(int i = 0; i < list.size(); i++){            paramsArray[i] = list.get(i);        }        /**         * 如果是用 setQueryString(paramsArray);方法的在restful的java端是用@QueryParam 獲取的         * 如果是用  postMethod.addParameter(new NameValuePair(entry.getKey(), entry.getValue()));;方法的在restful的java端是用@FormParam 獲取的         * */        getMethod.setQueryString(paramsArray);        //鏈接超時        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);        //讀取超時        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);        return httpConnect(httpClient, getMethod);    }    /**     * post請求     * @param url     * @param params     * @return     */    public static HttpClientResponse postHttp(String url, Map<String, String> params){        return postHttp(url, params, 60000);    }    public static  HttpClientResponse postHttp( String url, Map<String, String> params, int timeout){        HttpClient httpClient = new HttpClient();        httpClient.getParams().setContentCharset("UTF-8");        PostMethod postMethod = new PostMethod(url);        for (Map.Entry<String, String> entry : params.entrySet()) {            postMethod.addParameter(new NameValuePair(entry.getKey(), entry.getValue()));        }        //鏈接超時        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);        //讀取超時        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);        return httpConnect(httpClient, postMethod);    }    /**     * put請求     * @param url     * @param params     * put請求問題,這里的put請求,傳參的時候,putmethod只有setQueryString方法,這樣的話在restful后臺只能用@QueryParam來獲取     *              就不能用@FormParam來獲取參數,但是前端的js如果用put請求的話,是要用@FormParam獲取參數,所以這里出現了問題     * @return     */    public static HttpClientResponse putHttp(String url, Map<String, String> params){        return putHttp(url, params, 60000);    }    public static HttpClientResponse putHttp(String url, Map<String, String> params, int timeout){        try{            URL url1 = new URL(url);            //打開restful鏈接            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();            // 提交模式            conn.setRequestMethod("PUT");//POST GET PUT DELETE 必須大寫PUT,put為錯誤的            //設置訪問提交模式,表單提交            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");            conn.setConnectTimeout(timeout);//連接超時 單位毫秒            conn.setReadTimeout(timeout);//讀取超時 單位毫秒            conn.setDoOutput(true);// 是否輸入參數            StringBuffer paramsBuffer = new StringBuffer();            // 表單參數與get形式一樣            for (Map.Entry<String, String> entry : params.entrySet()) {                paramsBuffer.append(entry.getKey()).append("=").append(entry.getValue());            }            byte[] bypes = paramsBuffer.toString().getBytes();            conn.getOutputStream().write(bypes);// 輸入參數            //讀取請求返回值            InputStream inStream=conn.getInputStream();            InputStreamReader isr = new InputStreamReader(inStream);            BufferedReader br = new BufferedReader(isr);//為輸入流添加緩沖            String content = "";            String info = "";            while((info = br.readLine())!= null) {                content = content + info;            }            return new HttpClientResponse(new String(content.getBytes(), "UTF-8"));        } catch (Exception e){            return new HttpClientResponse(e.getMessage(), e);        }//        List<NameValuePair> list = new ArrayList<>();//        for(Map.Entry<String, String> param : params.entrySet()){//            list.add(new NameValuePair(param.getKey(), param.getValue()));//        }//        HttpClient httpClient = new HttpClient();//        PutMethod putMethod = new PutMethod(url);//        NameValuePair[] paramsArray = new NameValuePair[list.size()];//        for(int i = 0; i < list.size(); i++){//            paramsArray[i] = list.get(i);//        }//        putMethod.setQueryString(paramsArray);//        putMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");//        //鏈接超時//        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);//        //讀取超時//        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);//        return httpConnect(httpClient, putMethod);    }    /**     * delete請求     * @param url     * @param params     * @return     */    public static <T> HttpClientResponse deleteHttp(String url, Map<String, String> params){        return deleteHttp(url, params, 60000);    }    public static HttpClientResponse deleteHttp(String url, Map<String, String> params, int timeout){        List<NameValuePair> list = new ArrayList<>();        for(Map.Entry<String, String> param : params.entrySet()){            list.add(new NameValuePair(param.getKey(), param.getValue()));        }        NameValuePair[] paramsArray = new NameValuePair[list.size()];        for(int i = 0; i < list.size(); i++){            paramsArray[i] = list.get(i);        }        HttpClient httpClient = new HttpClient();        DeleteMethod deleteMethod = new DeleteMethod(url);        deleteMethod.setQueryString(paramsArray);        deleteMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");        //鏈接超時        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);        //讀取超時        httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);        return httpConnect(httpClient, deleteMethod);    }    public static HttpClientResponse httpConnect(HttpClient httpClient, HttpMethodBase httpMethodBase){        HttpClientResponse httpClientResponse = new HttpClientResponse();        httpClientResponse.setSuccess(true);        try{            httpClient.executeMethod(httpMethodBase);            ByteArrayOutputStream out = new ByteArrayOutputStream();            InputStream in = httpMethodBase.getResponseBodyAsStream();            InputStreamReader isr = new InputStreamReader(in);            BufferedReader br = new BufferedReader(isr);//為輸入流添加緩沖            String content = "";            String info = "";            while((info = br.readLine())!= null) {                content = content + info;            }            return new HttpClientResponse(content);        } catch (HttpException e){            e.printStackTrace();            httpClientResponse.setSuccess(false);            httpClientResponse.setMsg(e.getMessage());            httpClientResponse.setThrowable(e);        } catch (IOException e){            e.printStackTrace();            httpClientResponse.setSuccess(false);            httpClientResponse.setMsg(e.getMessage());            httpClientResponse.setThrowable(e);        } catch (Exception e){            e.printStackTrace();            httpClientResponse.setSuccess(false);            httpClientResponse.setMsg(e.getMessage());            httpClientResponse.setThrowable(e);        }  finally{            //釋放連接            httpMethodBase.releaseConnection();        }        return httpClientResponse;    }}

HttpClientResponse

package com.flyread.optwebcontainer.biz.httpRequest;import flyread.lang.result.SerialException;/** * http請求返回結果 * Created by sff on 2017/3/3. */public class HttpClientResponse {    //返回結果是否正確    private boolean isSuccess;    //返回的結果    private String content ;    //請求異常時提示信息    private String msg;    //請求異常    private Throwable throwable;    public HttpClientResponse() {    }    public HttpClientResponse(String content) {        this.content = content;        this.isSuccess = true;    }    public HttpClientResponse(String msg, Throwable cause) {        this.isSuccess = false;        this.msg = msg;        this.throwable = cause;    }    public HttpClientResponse(String content, boolean isSuccess, String msg, SerialException cause) {        this.content = content;        this.isSuccess = isSuccess;        this.msg = msg;        this.throwable = cause;    }    public Throwable getThrowable() {        return throwable;    }    public void setThrowable(Throwable throwable) {        this.throwable = throwable;    }    public boolean isSuccess() {        return isSuccess;    }    public void setSuccess(boolean success) {        isSuccess = success;    }    public String getContent() {        return content;    }    public void setContent(String content) {        this.content = content;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西吉县| 余庆县| 巴楚县| 遂平县| 盐津县| 海宁市| 高淳县| 黔江区| 元氏县| 化隆| 浮山县| 子长县| 凤山县| 烟台市| 荆州市| 兴安盟| 宜丰县| 迁西县| 沙湾县| 龙陵县| 大石桥市| 汽车| 温宿县| 双城市| 宣武区| 怀化市| 资溪县| 杭锦旗| 碌曲县| 枣强县| 南开区| 台北县| 乌恰县| 威远县| 永胜县| 大港区| 陈巴尔虎旗| 鄂州市| 吉水县| 阳东县| 南平市|