java通过http发送接受请求

项目开发的时候,我们使用webservice调用别人的数据,然后通过netty传输过来。但是,netty在传输的时候,会有数据过大传不过来的原因。这个时候,别人给我提议使用http接受数据。

思路就是在使用netty传输的时候,传不过来,改用http传输,这个时候数据已经是拿到了,发送过去。另一端接受即可。

上代码。

发送数据

public static String loginOfPost(String str) {
        HttpURLConnection conn = null;
        try {
            // 创建一个URL对象
            URL mURL = new URL("http://localhost:12001");
            // 调用URL的openConnection()方法,获取HttpURLConnection对象
            conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("POST");// 设置请求方法为post
            conn.setReadTimeout(10000);// 设置读取超时为5秒
            conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
            conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容

            // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
            OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
            out.write(str.getBytes());
            out.flush();
            out.close();
            int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFromInputStream(is);
                return state;
            } else {
//                Log.i(TAG, "访问失败" + responseCode);
                System.out.print("访问失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();// 关闭连接
            }
        }
        return null;
    }

接受数据

/**
     * 接受客服端发送的请求
     * @param map
     */
    private String serverAcceptRequest(Map map, String json,int port,String methodName) {
        StringBuffer sb = new StringBuffer();
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            while(true) {
                json = JSONArray.toJSONString(map);
                cwpService.sendMsgToIpa(UUID.randomUUID().toString(), methodName, json);
                Socket clientSocket = serverSocket.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                String temp;
                while((temp=in.readLine()) != null)
                    sb.append(temp);
                in.close();
                break;
            }
        } catch(Exception e) {
            System.out.println("ERROR: " + e.getMessage());
            System.exit(1);
        }
        return sb.toString();
    }

猜你喜欢

转载自blog.csdn.net/huaxin_sky/article/details/80090573