cccreator / Java

Accumulation And Mark
0 stars 0 forks source link

HttpURLConnection直接发送soap调用Webservice服务 #11

Open cccreator opened 5 years ago

cccreator commented 5 years ago

HttpURLConnection

任何网络连接都需要经过socket才能连接,HttpURLConnection不需要设置socket,所以,HttpURLConnection并不是底层的连接,而是底层连接上的一个请求。虽然底层的网络连接可以被多个HttpURLConnection实例共享,但是每一个HttpURLConnection实例只能发送一个请求。请求结束后,应该调用HttpURLConnection实例的InutStream或者OutputStream的close()方法以释放请求的网络资源,不过这种方式对于持久化连接没用,得用disconnect()方法关闭底层连接的socket。

HttpURLConnection的请求相应流程 1552810955(1)

  1. 创建HttpURLConnection
URL url = new URL("http://localhost:8080/xxx.do");    

URLConnection rulConnection = url.openConnection();// 此处的urlConnection对象实际上是根据URL的    
// 请求协议(此处是http)生成的URLConnection类    
// 的子类HttpURLConnection,故此处最好将其转化    
// 为HttpURLConnection类型的对象,以便用到    
// HttpURLConnection更多的API.如下:    

HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;  
  1. 设置HttpURLConnection参数
    
    // 设定请求的方法为"POST",默认是GET    
    httpUrlConnection.setRequestMethod("POST");    

// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
httpUrlConnection.setDoOutput(true);

// 设置是否从httpUrlConnection读入,默认情况下是true;
httpUrlConnection.setDoInput(true);

// Post 请求不能使用缓存
httpUrlConnection.setUseCaches(false);

// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");

// 连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
httpUrlConnection.connect();


3. URLConnection建立连接

    // 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,    
    // 所以在开发中不调用上述的connect()也可以)。    
    OutputStream outStrm = httpUrlConnection.getOutputStream();    
    //getInputStream()也同理

4. HttpURLConnection发送请求

// 现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。
ObjectOutputStream objOutputStrm = new ObjectOutputStream(outStrm);

// 向对象输出流写出数据,这些数据将存到内存缓冲区中
objOutputStrm.writeObject(new String("我是测试数据"));

// 刷新对象输出流,将任何字节都写入潜在的流中(些处为ObjectOutputStream)
objOutputStm.flush();

// 关闭流对象。此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中,
// 在调用下边的getInputStream()函数时才把准备好的http请求正式发送到服务器
objOutputStm.close();

cccreator commented 5 years ago

应用:使用HttpURLConnection调出行服务

/**
 * 福州调出行服务接口
 * @param stationId
 * @return
 */
public static List<Map<String,String>> getBusOnRoadByStation(String routeId,String stationId) {
        URL url = null;
        HttpURLConnection httpConn = null;
        List<Map<String,String>> list = null;
        String str = "";
        String urlPath = "地址+端口/BusService/Query_ByStationID/?RouteID=" + routeId + "&StationID=" + stationId;
        try{
                url = new URL( urlPath);
                URLConnection conn = url.openConnection();
                if (conn instanceof HttpURLConnection) {
                        httpConn = (HttpURLConnection) conn;
                        httpConn.setDoOutput(true);
                        httpConn.setDoInput(true);
                        //在传送json数据时注意设置Content-Type的值
                        httpConn.setRequestProperty("Content-Type", "application/json");
                        httpConn.setRequestMethod("GET");
                        JSONArray pointArray = new JSONArray();

                        int resultCode = httpConn.getResponseCode();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(httpConn.getInputStream()));
                        String lines;
                        StringBuffer returnData = new StringBuffer("");
                        while ((lines = reader.readLine()) != null) {
                                lines = new String(lines.getBytes(), "utf-8");
                                returnData.append(lines);
                        }

                        JSONArray jsonArray = JSONArray.parseArray(returnData.toString());
//                        Map<String,List<Map<String,String>>> map = new HashMap<>();
                        List<Map<String,String>> listResult = new ArrayList<>();
                        for(int i =0;i<jsonArray.size();i++){
//                                Map<String,List<Map<String,String>>> map = new HashMap<>();
                                Map<String,String> map = new HashMap<>();
                                JSONObject item =  jsonArray.getJSONObject(i);
                                String routeid = item.get("RouteID").toString();
                                String realTimeInfoList = item.get("RealtimeInfoList").toString();
                                map.put(routeid,realTimeInfoList);
                                listResult.add(map);
                        }
                        System.out.println(listResult);
                        reader.close();
                        return listResult;
                }
        }catch (Throwable t){
                t.printStackTrace();
                httpConn.disconnect();
        }finally{
                if(httpConn != null){
                        httpConn.disconnect();
                }
        }
        return list;//转换后的String对象
    }
cccreator commented 5 years ago

应用:使用HttpURLConnection调gps转换服务

    public String gpsSet(String longitude, String latitude) {
        URL url = null;
        String state = null;
        String lonAndlat = null;
        String gpsOffSet = longitude + "," + latitude;
        HttpURLConnection httpConn = null;

        try {
            url = new URL("http://gist.sz95000.com/coorconvert/coor_convert?ver=1.0&from=wgs84&to=wgs84&encrypt=1");
            URLConnection conn = url.openConnection();
            if (conn instanceof HttpURLConnection) {
                httpConn = (HttpURLConnection) conn;
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
                //在传送json数据时注意设置Content-Type的值
                httpConn.setRequestProperty("Content-Type", "application/json");
                httpConn.setRequestMethod("POST");
                JSONArray pointArray = new JSONArray();

                //以下是循环生成json对象并放入json数组
                JSONObject point = new JSONObject();
                point.put("type", 1);
//                point.put("id", "2321");
                point.put("point", gpsOffSet);
                pointArray.add(point);

                OutputStream outputStream = httpConn.getOutputStream();
                outputStream.write(pointArray.toString().getBytes("utf-8"));
                outputStream.flush();
                outputStream.close();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(httpConn.getInputStream()));
                String lines;
                StringBuffer returnData = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    returnData.append(lines);
                }
                //把返回值returnData转成json数组去解析
                /*JSONObject FOR = JSONObject.fromObject(returnData.toString());
                JSONArray arr = (JSONArray) FOR.get("objects");
                JSONObject resPoint = (JSONObject) arr.get(0);
                lonAndlat = resPoint.get("point").toString();

                System.out.println(returnData);*/

                reader.close();

            }

        } catch (Throwable t) {
            t.printStackTrace();
            httpConn.disconnect();
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();

            }
        }
        return lonAndlat;//转换后的String对象
    }
cccreator commented 5 years ago

关于IO和json相关访问:https://github.com/cccreator/Java/issues/12