HttpURLConnection get请求 添加json参数 亮哥代码实力见证

版权声明: https://blog.csdn.net/yz18931904/article/details/82857984

try {
            HashMap<String, Object> reqmap = new  HashMap<String,Object>();
            reqmap.put("username", "lilp21");
            reqmap.put("password","pass1234");
            JSONObject obj = new JSONObject(reqmap);
            System.out.println(obj.toString());
            String r = URLEncoder.encode(obj.toString(), "UTF-8");      
            String reqUrl = "http://erpuat.tk.cn/tkcnerp?api_s=ldap&api_m=login&data=" + r;
            String doInnerGet = HttpUtil.doInnerGet(reqUrl, ConstantConfig.HTTP_RETRY_NUM, ConstantConfig.HTTP_READ_TIMEOUT);
            System.out.println(doInnerGet);
        } catch (IOException e) {
            e.printStackTrace();
        }

public static String doInnerGet( String url, int retryNum, int readTimeout ) throws IOException {
        for ( int i = 1;; ++i ) {
            try {
                return doGet( url, readTimeout );
            } catch ( IOException e ) {
                if ( i == retryNum )
                    throw e;
                try {
                    log.info("INFO-->HttpUtil-->doInnerGet |param:url="+url+" |retryNum="+retryNum+"|readTimeout="+readTimeout);
                    Thread.sleep( 10 );
                } catch ( InterruptedException e1 ) {
                }
            }
        }
    }

    private static String doGet( String url, int readTimeout ) throws IOException {
        URL url1 = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            url1 = new URL( url );
            connection = (HttpURLConnection) url1.openConnection();
            connection.setConnectTimeout( 8000 );
            connection.setReadTimeout( readTimeout );
            connection.setRequestMethod( "GET" );
            connection.setInstanceFollowRedirects( true );
            connection.connect();
            reader = new BufferedReader( new InputStreamReader( connection.getInputStream(), "utf-8" ) );
            StringBuffer sb = new StringBuffer();
            String line;
            while ( ( line = reader.readLine() ) != null ) {
                sb.append( line ).append( "\n" );
            }
            reader.close();
            connection.disconnect();
            return sb.toString();
        } finally {
            if ( reader != null ) {
                try {
                    reader.close();
                } catch ( IOException e1 ) {
                }
            }
            if ( connection != null )
                connection.disconnect();
        }
    }

猜你喜欢

转载自blog.csdn.net/yz18931904/article/details/82857984