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 );

猜你喜欢

转载自www.cnblogs.com/lazyli/p/12664707.html