Java远程调用

1、HttpURLConnection
public static JSONObject sendHttp(String url, String param, String method) {
        JSONObject jsonObject = new JSONObject();
        try {
            URL connURL = new URL(url);
            HttpURLConnection httpCon = (HttpURLConnection) connURL.openConnection();

            // 设置http请求的头部
            httpCon.setUseCaches(false);// Post 请求不能使用缓存
            httpCon.setDoOutput(true); // http正文内,因此需要设为true, 默认情况下是false;
            httpCon.setDoInput(true); // 设置是否从httpUrlConnection读入,默认情况下是true;

            // 设定传送的内容类型是可序列化的java对象
            if ("POST".equals(method)) {
                httpCon.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
                httpCon.setRequestMethod(method); // 设定请求的方法为"POST",默认是GET
            } else if ("PUT".equals(method)) {
                httpCon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                httpCon.setRequestMethod(method); // 设定请求的方法为"POST",默认是GET
            }

            httpCon.setConnectTimeout(6000); // 连接主机的超时时间(单位:毫秒)
            httpCon.setReadTimeout(6000); // 从主机读取数据的超时时间(单位:毫秒)

            System.out.println("当前请求方式--->" + httpCon.getRequestMethod());
            // 写入http请求的正文
            DataOutputStream dataOutputStream = new DataOutputStream(httpCon.getOutputStream());

            System.out.println(param);

            dataOutputStream.write(param.getBytes("UTF-8"));
            dataOutputStream.flush();
            dataOutputStream.close();
            int responseCode = httpCon.getResponseCode();

            jsonObject.put("httpCode", responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) // 返回码正确
            {
                // 将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。
                BufferedReader bufReader = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
                StringBuffer sb = new StringBuffer();
                String line = "";
                while ((line = bufReader.readLine()) != null) {
                    sb.append(line);
                }
                bufReader.close();
                System.out.println(sb.toString());
                jsonObject.put("HttpData", sb.toString());
            } else {// 返回码错误,例如:404
                System.out.println("调用Http请求有异常!返回码为:" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("HttpCode", 400);
            jsonObject.put("HttpMessage", e.toString());
        }
        return jsonObject;
    }
2、HttpClient
public static String post(String serverUrl, String param){
        PostMethod method = new PostMethod(serverUrl);
        Map<String, String> params = new HashMap<String, String>();
        params.put("params", param);
        try {
            HttpClient http = new HttpClient();
            http.setConnectionTimeout(25000);
            http.setTimeout(25000);
            method.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            if (param != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    method.addParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
                }
            }
            int status = http.executeMethod(method);
            log.info("调用接口状态" + status);
            String resp = method.getResponseBodyAsString();
            System.out.println(resp);
            if (status == 200) {
                return resp;
            } else if (status == 500) {
                log.info("调用接口失败+"+status);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally
        {
            method.releaseConnection();
        }
        return "";
    }
3、HttpURLConnection和HttpClient的区别
  • 1、HttpClient比HttpURLConnection功能更强大,但是做java建议用前者,安卓建议用后者
  • 2、这两者都支持HTTPS,streaming 上传与下载,配置超时时间,IPv6, 以及连接池。
  • 3.区别
    HttpClient是个很不错的开源框架,封装了访问http的请求头,参数,内容体,响应等等,
    HttpURLConnection是java的标准类,什么都没封装,用起来太原始,不方便,比如重访问的自定义,以及一些高级功能等。
    在一般情况下,如果只是需要Web站点的某个简单页面提交请求并获取服务器响应,HttpURLConnection完全可以胜任。但在绝大部分情况下,Web站点的网页可能没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面。在这种情况下,就需要涉及Session、Cookie的处理了,如果打算使用HttpURLConnection来处理这些细节,当然也是可能实现的,只是处理起来难度就大了。
    HttpClient更方便更强大的解决了HttpURLConnection能做到或者不能做到的事情,HttpClient模块提供的两大类HttpPost和HttpGet实现Http请求:
    HttpPost —— 传送的数据量较大,一般被默认为不受限制。一般用于发送一些表单数据,传输数据更安全
    HttpGet —— 传送的数据量较小,不能大于2KB。一般用于请求获取一些信息,执行效率更高
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值