调用Restful接口【HttpURLConnection、HttpClients】

一、区别

1. HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。采用流式处理,比较便于流量管控、处理大的文件或参数

2. HttpClient 是Apache的一个三方网络框架,网络请求做了完善的封装,api众多,用起来比较方便,开发快。

二、HttpURLConnection实现调用Restful接口

public static void main(String[] args) throws Exception{
    String url = "http://localhost:8080/gjxx-system-web/getBusiness?licnum=" + "123&organiz="+"345";
    URL urlUtil = new URL(url);
    /**
     * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类的子类HttpURLConnection,
     * 故此处最好将其转化为HttpURLConnection类型的对象,以便用到HttpURLConnection更多的API.
     */
    HttpURLConnection urlConnnection = (HttpURLConnection) urlUtil.openConnection();
    //设定请求的方法为"POST",默认是GET 
    urlConnnection.setRequestMethod("POST");
    //设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
    urlConnnection.setDoOutput(true);
    //设置是否从httpUrlConnection读入,默认情况下是true; 
    urlConnnection.setDoInput(true);
    //Post请求不能使用缓存
    urlConnnection.setUseCaches(true);
    //设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) 
    urlConnnection.setRequestProperty("Content-Type", "application/json");
    //设置连接超时
    urlConnnection.setConnectTimeout(10000);
    //设置读取超时(从输入流读取时的超时)
    urlConnnection.setReadTimeout(20000);
    /**
     * connect()会按照之前set生成HttpHeader
     * 正文的内容是通过outputStream流写入
     */
    // 此处getOutputStream会隐含的进行connect()
    OutputStream outputStream = urlConnnection.getOutputStream();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("licnum", "123");
    jsonObject.put("organiz", "345");
    //向对象输出流写出数据,outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络
    outputStream.write(jsonObject.toString().getBytes("utf-8"));
    //刷新对象输出流,将任何字节都写入潜在的流中(些处为outputStream) 
    outputStream.flush();
    //关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中, 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器 
    outputStream.close();
    /**
     * 实际发送请求的代码段在下面
     */
    // 调用HttpURLConnection连接对象的getInputStream()函数,将内存缓冲区中封装好的完整的HTTP请求电文发送到服务端。 
    InputStream inputStream = urlConnnection.getInputStream(); // <===注意,实际发送请求的代码段就在这里 
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
    String line = "";
    String result = "";
    for (; (line = br.readLine()) != null; result += line) {
        ;
    }
    System.out.println(result);
    br.close();
}

三、HttpClient实现调用Restful接口

方式一:Http调用第三方接口代码

/**
 * 房融界接口对接
 * @return
 */
public Map<String,Object> frjRequest(){
    String url="房融界提供的接口地址";
    String result = "";
    HttpPost httppost=new HttpPost(url); //建立HttpPost对象
    CloseableHttpClient client = HttpClients.createDefault();//创建HttpClient对象

    try {
        //添加参数
        List<NameValuePair> paramsList=new ArrayList<NameValuePair>();
        paramsList.add(new BasicNameValuePair("键","值"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramsList, "UTF-8");

        //设置请求和传输时长
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setSocketTimeout(120000);
        builder.setConnectTimeout(60000);
        RequestConfig config = builder.build();

        httppost.setEntity(entity);
        httppost.setConfig(config);

        //发送Post
        CloseableHttpResponse response = client.execute(httppost);
        HttpEntity httpEntity = response.getEntity();
        if (httpEntity != null) {
            result = EntityUtils.toString(httpEntity, "UTF-8");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            client.close();
            httppost.releaseConnection();
        } catch (IOException e) {
            logger.info(e.toString(), e);
        }
    }
    return JSON.parseObject(result, Map.class);
}

 方法二:传递JSON格式请求

/**
 * 发送json流数据*/
public static String postWithJSON(String url, String jsonParam) throws Exception {
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();
    String respContent = null;
    StringEntity entity = new StringEntity(jsonParam, "utf-8");//解决中文乱码问题
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpResponse resp = client.execute(httpPost);
    if (resp.getStatusLine().getStatusCode() == 200) {
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he, "UTF-8");
    }
    return respContent;
}

注意:

//Map --> JSONString
Map<String,Object> param = new HashMap<>();
param.put("name",name);
param.put("phone",phone);
String jsonParam = JSONUtils.toJSONString(param);
//JSONString --> JSONObj
JSONObject resultObj = JSONObject.parseObject(jsonParam);

方法三:传递字符串格式数据

public static String postWithString(String url, String stringParam) throws Exception {
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();
    String respContent = null;
    StringEntity entity = new StringEntity(stringParam, "utf-8");//解决中文乱码问题
    entity.setContentEncoding("UTF-8");
    entity.setContentType("text");
    httpPost.setEntity(entity);
    HttpResponse resp = client.execute(httpPost);
    if (resp.getStatusLine().getStatusCode() == 200) {
        HttpEntity he = resp.getEntity();
        respContent = EntityUtils.toString(he, "UTF-8");
    }
    return respContent;
}

 

posted @ 2018-06-04 15:35  yifanSJ  阅读(951)  评论(0编辑  收藏  举报