java發起form請求(有參數,無參數)


1、無參請求

/**
     * 無參數請求
     * @param url
     * @return
     */
    public static String sendNoPara(String url){
        try {
            PostMethod postMethod = null;
            postMethod = new PostMethod(url) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            //參數設置,需要注意的就是里邊不能傳NULL,要傳空字符串

            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 執行POST方法
            String result = postMethod.getResponseBodyAsString() ;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

  2、有參數請求

/**
     * 發送Post請求,請求參數格式為form;
     * @return
     */
    public static String sendByForm(String url, NameValuePair[] data){
        try {
            //String postURL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage";
            PostMethod postMethod = null;
            postMethod = new PostMethod(url) ;
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
            //參數設置,需要注意的就是里邊不能傳NULL,要傳空字符串
            postMethod.setRequestBody(data);
            org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
            int response = httpClient.executeMethod(postMethod); // 執行POST方法
            InputStream in = postMethod.getResponseBodyAsStream();
            //下面將stream轉換為String
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            char[] b = new char[4096];
            for(int n; (n = isr.read(b)) != -1;) {
                sb.append(new String(b, 0, n));
            }
            String returnStr = sb.toString();

            return returnStr;
        } catch (Exception e) {
            // logger.info("請求異常"+e.getMessage(),e);
            e.printStackTrace();
        }
        return null;
    }

  參數:

NameValuePair[] data = {
new NameValuePair("image",base64Str)
};
String result = RequestInterfaceUtil.sendByForm(url,data );


免責聲明!

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



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