本人微信公众号"aeolian"~

接口调用方法

上一篇写了用jersey写了入门级的restful接口,并且通过jersey框架调用,后来想了想应该还有其他接口调用的方法,除了ajax方法外还找到了两种方法java的URLapache的httpclient。

java的URL

/**
     * @param path    请求路径
     * @param method    请求方法
     * @param params    参数
     * @return
     * @throws IOException
     */
    public static String sendPostByUrl(String path,String method,String params) throws IOException{
        BufferedReader in=null;
        java.net.HttpURLConnection conn=null;
        String msg = "";// 保存调用http服务后的响应信息
        try{
            java.net.URL url = new java.net.URL(path);
            conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setRequestMethod(method.toUpperCase());//请求的方法get,post,put,delete
            conn.setConnectTimeout(5 * 1000);// 设置连接超时时间为5秒 
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒 
            conn.setDoOutput(true);// 使用 URL 连接进行输出,则将 DoOutput标志设置为 true
            
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            //conn.setRequestProperty("Content-Encoding","gzip");
            conn.setRequestProperty("Content-Length", String.valueOf(params==null?"":params.length()));
            if (params!=null&&!params.isEmpty()) {
                OutputStream outStream = conn.getOutputStream();// 返回写入到此连接的输出流
                outStream.write(params.getBytes());
                outStream.close();//关闭流
            }
            if (conn.getResponseCode() == 200) {
                // HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码
                in = new BufferedReader(new InputStreamReader(
                        (InputStream) conn.getInputStream(), "UTF-8"));
                msg = in.readLine();
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            if(null!=in)
            {
                in.close();
            }
            if(null!=conn)
            {
                conn.disconnect();
            }
        }
        return msg;
    }

源码

Apache的Httpclient

Httpclient官网中下载httpclient.jar和httpcore.jar,引入到项目中

    /**
     * @param path    路径
     * @param param    参数
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static void getMessage(String path,String param) throws ClientProtocolException, IOException {
        path=path+"/"+param;  
        //1.创建客户端访问服务器的httpclient对象   打开浏览器  
        HttpClient httpclient=new DefaultHttpClient();  
        //2.以请求的连接地址创建get请求对象     浏览器中输入网址  
        HttpGet httpget=new HttpGet(path);  
        httpget.setHeader("Accept", "");
        //3.向服务器端发送请求 并且获取响应对象  浏览器中输入网址点击回车
        HttpResponse response=httpclient.execute(httpget);
        //4.获取响应对象中的响应码
        StatusLine statusLine=response.getStatusLine();//获取请求对象中的响应行对象
        System.out.println("Response status: " + response.getStatusLine());   //打印响应状态
        int responseCode=statusLine.getStatusCode();//从状态行中获取状态码
        if(responseCode==200){
            //5.获取HttpEntity消息载体对象  可以接收和发送消息
            HttpEntity entity=response.getEntity();
            // 打印响应内容长度
            System.out.println("Response content length: " + entity.getContentLength());
            //EntityUtils中的toString()方法转换服务器的响应数据
            String str=EntityUtils.toString(entity, "utf-8");
            System.out.println("Response content:"+str);
            
            //6.从消息载体对象中获取操作的读取流对象  
            /*InputStream input=entity.getContent();  
            BufferedReader br=new BufferedReader(new InputStreamReader(input));  
            String str1=br.readLine();  
            String result=new String(str1.getBytes("gbk"), "utf-8");  
            System.out.println("服务器的响应是:"+result);  
            br.close();  
            input.close();  */
        }else{  
            System.out.println("响应失败!");  
        }  
    }  

源码

点赞

Leave a Reply

Your email address will not be published. Required fields are marked *